简体   繁体   中英

Javascript set selected value of dropdownlist by text

I am using Jquery Datatables with inline editing. I have a hardcoded dropdownlist which is beeing created for each row dynamicly.

<select class="form-control edit-mode" id="Status">
<option>A</option>
<option>B</option>
<option>C</option>
</select>

So to get the value of the currently selected item I use

var tr = $(this).parents('tr:first');
var status = tr.find('#Status').val();

And the value I want to set it to is in the label next to it. So I get the value of that with:

var stat = tr.find('#lbl_Status').html();

So how do I set the selected value of the dropdownlist to the stat variable?

I have tried using the other solutions I found on Stackoverflow but they are not working since I can't seem to get the whole element or something. Since .length is not working on the status element. And I cannot use the normal document.getElementById method since it can be multiple select lists with the same ID.

F.ex with this solution:

$(document).on("click", ".edit-action", function (e) {
    var tr = $(this).parents('tr:first');
    var stat = tr.find('#lbl_Status').html();

    var status = tr.find('#Status');

for (var i = 0; i < status.options.length; i++) {
    if (status.options[i].text === stat) {
        status.selectedIndex = i;
        break;
        }
    }
});

I get: Uncaught TypeError: Cannot read property 'length' of undefined

status is jquery object,Use:

status.find('option').length;

or convert to javascript object and use:

status[0].options.length

Demo

I solved this by just using this line instead of the whole for loop.

status.find("option:contains("+ stat +")").attr('selected', true);

Thanks for pointing out that it was a Jquery object which led me to the answer :)

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