jquery - dynamically changing the option text is not working

Please find the jsfiddle

https://jsfiddle.net/qs008so7/

I have an option box in html and I am trying to set the option using jquery. But its not working . Please find the code below.

If I call the code in console and I am able to see the expected html is getting returned. Means , the changes are properly affected int he DOM but it is not getting reflected in UI. . You can see my jfiddle .

HTML:

<select class="form-control" name="test" id="test">
    <option value="0">Disabled</option>
    <option value="1">Enabled</option>
</select>

JS:

setGivenOption(test,"Enabled");
setGivenOption(test,"Disabled");

function setGivenOption(elementId, option) {
    //Make all the old selections to null
    $(elementId).each(function () {
        $('option', this).each(function () {
            $(this).attr('selected', null);
        });
    });
    //set the given option
    $(elementId).find(">option:contains('" + option + "')").attr("selected", "selected");
}

Thanks.

Answers 1

  • Simply

    $(elementId).find('option:contains(' + option + ')').attr('selected', true);
    

    That will diselect whatever that was selected and select the new option


Related Articles