简体   繁体   中英

How to create a drop down that takes input from a text field and show the position on text

I am creating a drop down that takes input like a normal text field and show the position of the text. For this I have created a drop down and a text field and hide the drop down under text field. Now I want to write a Jquery that will take input from the text field and matches it with drop down and if there is a match then show the option from the drop down. Is it possible?

Check this example

Js:

var options=["First","Second"];
$("#data").on('keyup',function(){
    var v = $(this).val();
    $("#options").html("");
    $.each(options,function(index){
        if(options[index].indexOf(v) > -1){
            $("#options").append("<li>"+options[index]+"</li>");
        }
    })
})

**There are better and more efficient ways to do this you may use this as example to start with.

This is your:

HTML

Textbox: <input type="text" /><br />
Text and position: <span></span>
<select style="display: none;">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="vw">VW</option>
    <option value="audi" selected>Audi</option>
</select>

JQUERY

$("input").on('change keyup paste', function(){
    var theInput = this;
    $.each($("select option"), function(index, option){
        if ($(option).val().toLowerCase().trim() == 
            $(theInput).val().toLowerCase().trim()){
            var textToShow = $(option).val().trim() + " " + Number(index + 1);
            $("span").text(textToShow);
            $("select").val($(theInput).val().toLowerCase().trim());
        } else {
            $("span").text("");
        }
    });
});

https://jsfiddle.net/L000qqr9/1/

and here is another quick example as well

http://codepen.io/anon/pen/LVebbr

 var $inputField = $('#inputText'), $dropdown = $('.dropdown'); $inputField.on('keyup', function(){ var _value = $(this).val(); $dropdown.children('li').each(function(){ ( $(this).html().indexOf(_value) > -1 ) ? $(this).css('opacity', '1') : $(this).css('opacity', '0'); }); }); 
 .dropdown li{ opacity:0 } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="text" id="inputText" /> <ul class="dropdown"> <li>op1</li> <li>op2</li> <li>op3</li> <li>op3</li> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM