简体   繁体   中英

How to make 2nd drop down list auto select value based on 1st drop down value

I have two drop down list, one for Client and Location. I would like the location drop down to auto select a value based on the selected Client option.

This is the script i came up with but the value is not being displayed on the location drop down.

function defaultLocation () {
  var client2 = document.getElementById('clientList2');
  if (client2.value == "Arm") {
    document.getElementById('locationList2').value == "Cambridge";
  }
}

As of now, I want the value to be auto selected when the Client option is chosen with no need to click a button.

UPDATE: I would still like the user to be able to choose something else from the location list if the default option is not wanted? How would i do that as of right now, once "Arm" is selected, i can't change the location option

To assign value, you have to use assignment operator ( = ) not == :

document.getElementById('locationList2').value = "Cambridge";

once "Arm" is selected, i can't change the location option

But I am unable to raise the issue in the following:

 function defaultLocation () { var client2 = document.getElementById('clientList2'); if (client2.value == "Arm") { document.getElementById('locationList2').value = "Cambridge"; } }
 <select id="clientList2" onchange="defaultLocation()"> <option value="c1">Client 1</option> <option value="Arm">Arm</option> </select> <select id="locationList2"> <option value="l1">Location 1</option> <option value="Cambridge">Cambridge</option> </select>

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