简体   繁体   中英

select first drop down to be the same value as the other drop down

I would like to select all drop down to be the same as the value selected from the primary dropdown. I got it to work if there is one select selected from the primary dropdown, but will not work if there are two selects, I have added some code below for your information.

HTML:

<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select Name</option>
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
</select>

<select id="Qualifications" name="Qualifications">
    <option value="select">select</option>
    <option value="Pass">Pass</option>
    <option value="Fail">Fail</option>
</select>

<select  id="Qualifications" name="Qualifications">
    <option value="select">select</option>
    <option value="Pass">Pass</option>
    <option value="Fail">Fail</option>
</select>

JavaScript:

function setDropDown() {
    var index_name=document.QualificationForm.ForceSelection.selectedIndex;  

    document.QualificationForm.Qualifications.selectedIndex=index_name;

}

Try this

function setDropDown() {
   var index_name = 
        document.getElementsByName('ForceSelection')[0].selectedIndex;
   var others = document.getElementsByName('Qualifications');
   for (i = 0; i < others.length; i++)
       others[i].selectedIndex = index_name;
}

You could possibly use the following, though currently untested:

function setDropDown(el){
    if (!el) {
        return false;
    }
    else {
        var index = el.selectedIndex,
            selects = document.getElementsByName('qualifications');
            for (var i=0, len=selects.length; i<len; i++){
                selects[i].selectedIndex = index;
            }
    }
}

This requires that you pass the #ForceSelection select element into the function, and so is called like:

<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown(this);">
<!-- other stuff -->
</select>

The selectedIndex of this passed-in element will be applied to the other select elements with the name of qualifications .

Also, please allow me to reiterate: an id must be unique within the document in order to be valid HTML.

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