setSelectedIndex byname and byval

Set active (Selected) item in listbox using javascript
Imported and modified from https://www.daftlogic.com/information-programmatically-preselect-dropdown-using-javascript.htm


Public

Tested

My Own Work
HTML example:

<select id="ddl_example4" name="ddl_example4">
<option value="AA">item1</option>
<option value="BB">item2</option>
<option value="CC">item3</option>
<option value="DD">item4</option>
<option value="EE">item5</option>
<option value="FF">item6</option>
</select>


<script>

// to change selection using name of option
setSelectedIndex_byname(document.getElementById('ddl_example4'),"item4");
function setSelectedIndex_byname(s, v) {
    for (var i = 0; i < s.options.length; i++) {
        if (s.options[i].text == v) {
            s.options[i].selected = true;
            return;
        }
    }
}


// to change selection using value of option
setSelectedIndex_byval(document.getElementById("ddl_example4"),"BB");
function setSelectedIndex_byval(s, valsearch) {
    // Loop through all the items in drop down list
    for (i = 0; i< s.options.length; i++) {
        if (s.options[i].value == valsearch) { // Item is found. Set its property and exit
            s.options[i].selected = true;
            break;
        }
    }
    return;
}


</script>




Views 427 Downloads 86

JS+JQuery Components
ANmarAmdeen
813
Attachments
Revisions

v1.0