简体   繁体   中英

Using jQuery to replace an option element in one select box with another?

I have two select boxes, one of which is dynamically populated. The second box I would like to replace the option element with whatever is selected. At the moment, I have it working with this:

    var currentManCodeSelected = $('#sltmanu').find(':selected')[i].value;
    var currentManCodeName = $('#sltmanu').find(':selected')[i].text;

    $('#sltmanuCurrent option:first').replaceWith("<option value='" + currentManCodeSelected + "'>" + currentManCodeName + "</option>");

Is there a better way of doing this? A shorter and more elegant way?

You can do that like following;

HTML:

<select id="left">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

<select id="right">
    <option value="d">d</option>
    <option value="e">e</option>
    <option value="f">f</option>
</select>

JS:

$(document).ready(function() {
    $("#left").on('change', function() {
        $('#right :selected').val($('#left :selected').val()).text($('#left :selected').text());
    });
});

Here is a working fiddle: http://jsfiddle.net/Azugu/

只需更改值和文本,而不是替换整个元素

$('#sltmanuCurrent option:first').val(currentManCodeSelected).text(currentManCodeName);

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