How to get index of value in dropdown in javascript?

I have a dropdown on my aspx page. I want to manually set the selected value that exists in the drop-down list. this is the value i get in var. I want to set this value as the selected value when initializing the page. I want this in javascript. is there a property for the dropdown like ddp.SelectedValue = '40 '..? here I do not know the index 40 in the list.

+3
source share
3 answers

selectedIndex is a property of HTMLSelectElement, so you can do the following:

<select id="foo"><option>Zero<option>One<option>Two</select>
<script>
document.getElementById('foo').selectedIndex = 1;  // Selects option "One"
</script>

And given the OPTION element, you can get its index using the property index:

<select><option>Zero<option id="bar">One<option>Two</select>
<script>
alert(document.getElementById('bar').index);  // alerts "1"
</script>
+6
source

select, option, selected:

var options= document.getElementById('ddp').options;
for (var i= 0; n= options.length; i<n; i++) {
    if (options[i].value==='40') {
        options[i].selected= true;
        break;
    }
}

. , .

:

document.getElementById('ddp').value= '40';

HTML5, , , , , ( IE9) IE.

+6
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery 1.6.2.min.js" />
<script language="JavaScript">
    $(function() {
        quickSelect();
        // Handler for .ready() called.
    });
    function quickSelect() {
        var bnd = "40";
        if (bnd != "") {
            $("#ddp option[value='" + bnd + "']").attr("selected", "selected");
        }
    }
</script>
+3
source

Source: https://habr.com/ru/post/1784248/


All Articles