简体   繁体   中英

Change form select option when click and select another option

I have something like this until now.

<form> 
       <select name='country'>
            <option value='0'>Select one country</option>
            <option value='germany'>Germany</option>
            <option value='england'>England</option>
       </select>
       <select name='city'>
            <option value=''>Select one city</option>
            <option value='stuttgart'>Stuttgard</option>
            <option value='munchen'>Munchen</option>
       </select>
       <input type='submit' name='submit' value='Search'>
</form>

What i want: when someone choose one country like germany, next option value should be germans cities. But if i choose England i want to modify next option value and text to have something like this with english cities:

     <select name='city'>
            <option value=''>Select one city</option>
            <option value='london'>London</option>
            <option value='manchester'>Manchester</option>
     </select>

I dont know how to do this, please inform me or redirect to some online stufs or tutorials, i dont want all the codes from you, but i have no idea. Thanks!

If you're not using jQuery already you probably should be as tasks like this become much easier with it. You'd want to do something like this:

$("select[name='country']").on("change",function(){
    var currentValue = $(this).val();
    var options = "";
    //switch on currentValue and build options string
    $("select[name='city']").html(options);
});

It is very depends on how you store the value and what javascript framework that you are using. This is the very simple and pure javascript implementation.

 var c1 = ["City 1-1", "City 1-2"]; var c2 = ["City 2-1", "City 2-2"]; var x = [c1, c2]; function onCountryChanged(s) { var cities = document.getElementById("city"); if (s.value > 0) { var v = ""; for (var i = 0; i < x[s.value - 1].length; i++) { v += "<option value='" + x[s.value - 1][i] + "'>" + x[s.value - 1][i] + "</option>" } cities.innerHTML = v; } else { cities.innerHTML = ""; } } 
 <select onchange="onCountryChanged(this)"> <option value="0">Select Country</option> <option value="1">Country 1</option> <option value="2">Country 2</option> </select> <select id="city"> </select> 

  var countries = []; countries['germany'] = ["München", "Berlin", "Stuttgart"]; countries['england'] = ["London", "Manchester", "Liverpool"]; document.querySelector("select[name='country']").addEventListener("change", function(){ var element = countries[this.value.toString().toLowerCase()]; if (element) { //clone: var select = document.querySelector("select[name='city']").cloneNode(); var node = document.createElement("option"); node.value = 0; node.setAttribute("disabled", true); node.setAttribute("selected", true); node.textContent = "Select a city"; select.appendChild(node); countries[this.value.toString().toLowerCase()].forEach(function(element){ var node = document.createElement("option"); node.value = element; node.textContent = element; select.appendChild(node); }); document.querySelector("select[name='city']").parentElement.replaceChild(select, document.querySelector("select[name='city']")); } }, false); 
 <form> <select name='country'> <option value='0'>Select one country</option> <option value='germany'>Germany</option> <option value='england'>England</option> </select> <select name='city'> </select> <input type='submit' name='submit' value='Search'> </form> 

This will do it I guess. I hope you can see what it does.

  1. Created arrays containing the cities.
  2. When the value of country select is changed, the event change fires.
  3. If the value matches an item from the countries array, then continue.
  4. Iterate over all values and append them to a cloned select.
  5. Replace the old select with the new one.

I'm cloning the old select so we can add nodes in memory and then replace the whole select at once. This prevents the browser from redrawing every time a new option is added, saving resources.

Another way without jQuery, using data-attributes :

 var countrySelect = document.querySelector('[name=country]'); var cityOptions = document.querySelectorAll('option[data-country]'); countrySelect.addEventListener('change', function(){ for (var i = 0; i < cityOptions.length; i++){ var opt = cityOptions[i]; opt.style.display = (opt.getAttribute('data-country') === this.value) ? '' : 'none'; } }, false); 
 <select name='country'> <option value='0'>Select one country</option> <option value='germany'>Germany</option> <option value='england'>England</option> </select> <select name='city'> <option value=''>Select one city</option> <option data-country="england" value='london'>London</option> <option data-country="england" value='manchester'>Manchester</option> <option data-country="germany" value='stuttgart'>Stuttgard</option> <option data-country="germany" value='munchen'>Munchen</option> </select> 

您可以使用层次选择插件等: jquery-select-hierarchy

I found an solutions, is not very well optimized but it works: http://jsfiddle.net/YPsqQ/772/

$(document).ready(function() {

$("#country").change(function() {
    var val = $(this).val();
    if (val == "1") {
        $("#city").html("<option value='berlin'>Berlin</option><option value='munchen'>Munchen</option>");
    } else if (val == "2") {
        $("#city").html("<option value='london'>London</option><option value='manchester'>Manchester</option>");

    } 
});

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