简体   繁体   中英

Change select box value text

I got one text box and one select box.

<input type="text" />

<select>
<option value=1>Test1</option>
<option value=2>Test2</option>
</select>

Now i want when user type anything in text box, to change value=2 text.

I tried this, but looks like don't work.

$(document).ready(function () {
$("#textbox").keyup(function () {




    $("select#sync[value='2']").text($(this).val());
});

});

Apart from the fact that you haven't given the elements IDs, the problem is that you need to access the <option> element (that one has a value of 2 - there is no <select value=2> ). Also, IDs are unique, so using select#sync is (should be) the same as #sync :

$("#sync option[value='2']")
<input type="text" id="textbox" />
<select>
   <option value="1">Test1</option>
   <option value="2">Test2</option>
</select>​

$(document).ready(function () {
    $("#textbox").keyup(function() {
       $("select option[value='2']").text($(this).val());
    });​
});

http://jsfiddle.net/gxaWE/

you can try

$("#sync").val($(this).val());

provided that the user only types the value that is in range

DEMO

$("#text_box").keyup(function() {
 $("#sync option[value='2']").text($(this).val());
});

​ ​

Here is fiddle showing it working: http://jsfiddle.net/bRw8Z/1/

It changes select option number 2 text. Is that what you wanted?

I see a few problems here:

  1. It doesn't make sense to set the innerText of a <select> element; you want to set its value instead,
  2. The #textbox selector wouldn't actually select anything.
  3. If your input did not exactly match an <option> 's value attribute, the first <option> would be selected.

This snippet will select an <option> if its value attribute matches the value of the text input.

$(document).ready(function () {
    $("input").keyup(function () {
        var $select = $("select"),
            value = $(this).val();
        if($select.find('option[value="' + value + '"]').length){
            $select.val(value);
        }
    });
});​

http://jsfiddle.net/2XxRQ/1/

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