简体   繁体   中英

Compare select dropdown value with another input and display matched one

HTML code:

<div class="controls" id="display">
<input type="text" name="demos" class="" value="1" id="displays"/>
<select class="input-medium">
 <option value="">Select</option>
 <option value="1">II</option>
 <option value="2">AS</option>
 <option value="3">AR</option>
</select>
</div>

Jquery code:

$("input[name='demos']").each(function(i,e){
  var SValue = $('#displays').val();   
     $('option[value=' + SValue + ']').attr('selected',true);   
}); 

I will be displaying the above html code as dynamic one for multiple times.

I will be comparing the value of #displays with the select options and make the select option as selected.

The value in #displays comes from database.

Since, am using multiple times the above html code when I pass the different values from database to that multiple code. All the multiple code shows only the first html code selected value.

However, I want all the multiple html code to show the selected value to their respective #displays.

In debug I found that $("input[name='demos']").each(function(i,e){ is not performing correctly because when i put console for Svalue it shows only the first html code input value for all the multiple html codes.

How can I fix this??

try

$("input#displays").each(function(i,e){

});

In HTML, the ID attribute is unique. You cannot use the same ID for more than one control in the same page. So, you'll need to use another approach.

I would do something like:

$("div.controls").each(function() {
    $(this).children("select").eq(0).val($(this).children("input").eq(0).val());
});

EDIT: And it works, I've just made this demo !

Try this:

$("#displays").blur(function () {
    var data = $(this).val();
    $("#select > option").each(function () {
        if (this.value == data) 
            $(this).attr("selected", "selected");       
    });
 });

This example will get the input from user then the system will select the matching value.

Here is the fiddle: http://jsfiddle.net/t6kBY/

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