最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Country and State selection using html and Javascript - Stack Overflow

programmeradmin4浏览0评论

I have applied the logic in view.jsp in Liferay to show the state list on State drop down based on the Country selected from the Country drop down. I have used html and java script to achieve this goal of showing the state drop down for the selected country from drop down list. Currently, when I first load the form, both of the Country and the state label with drop down is displaying. The state drop down is empty at first. Then when I select country, Example: USA, state drop down is changed to the state list related to USA which is working as expected. But, I want to not show the state drop down and State label at first when form is loaded as it will be empty and there will be "Select Country" option only selected in Country drop down. This is not working for me. Any idea what should I do to make State label and drop down to show at first when form loads and just to show state drop down list only when the country is selected from Country drop down?

Below is the html and java script code that I have:

<select name="<portlet:namespace/>Country" id="countryId" onchange="javascript:countryChange()">
        <option value="0">Select Country</option>
        <option value='US'>United States</option>
        <option value='CA'>Canada</option>
</select>
<label id="stateLabel">State:</label>  
<select name="<portlet:namespace/>State" id="stateId">
</select>

<!--Country and State Change Javascript-->
<script>
function CountryChange() {
    var countryState = [
        [
            'US', [
            ['', 'State/Province'],
            ['AL', 'Alabama'],
            ['AK', 'Alaska'],
            ['AZ', 'Arizona'],
            ['AR', 'Arkansas'],
  ], ],
[
            'CA', [
            ['', 'State/Province'],
            ['AB', 'Alberta'],
            ['BC', 'British Columbia'],
            ['MB', 'Manitoba'],
            ['NB', 'New Brunswick'],
  ]]
   ];

    var countryElement = document.getElementById('countryId');
    var stateElement = document.getElementById('stateId');
    var stateLabelElement = document.getElementById('stateLabel');

if (countryElement && stateElement) {
        var listOfState = [
            ['XX', 'None']
        ];

        var currentCountry = countryElement.options[countryElement.selectedIndex].value;
        for (var i = 0; i < countryState.length; i++) {
            if (currentCountry == countryState[i][0]) {
                listOfState = countryState[i][1];
            }
        }
        if (listOfstate.length < 2) 
            {
            stateElement.style.display = 'none';
            stateLabelElement.style.display = 'none';
            }
    else 
        {
        stateElement.style.display = 'inline';
        stateLabelElement.style.display = 'inline';
        }
        var selectedState;
        for (var i = 0; i < stateElement.length; i++) {
            if (stateElement.options[i].selected === true) {
                selectedState = stateElement.options[i].value;
            }     
        }
        stateElement.options.length = 0;
        for (var i = 0; i < listOfState.length; i++) {
            stateElement.options[i] = new Option(listOfState[i][1], listOfState[i][0]);
            if (listOfState[i][0] == selectedState) {
                stateElement.options[i].selected = true;
            }    
        }      
    }
}
</script>

I have applied the logic in view.jsp in Liferay to show the state list on State drop down based on the Country selected from the Country drop down. I have used html and java script to achieve this goal of showing the state drop down for the selected country from drop down list. Currently, when I first load the form, both of the Country and the state label with drop down is displaying. The state drop down is empty at first. Then when I select country, Example: USA, state drop down is changed to the state list related to USA which is working as expected. But, I want to not show the state drop down and State label at first when form is loaded as it will be empty and there will be "Select Country" option only selected in Country drop down. This is not working for me. Any idea what should I do to make State label and drop down to show at first when form loads and just to show state drop down list only when the country is selected from Country drop down?

Below is the html and java script code that I have:

<select name="<portlet:namespace/>Country" id="countryId" onchange="javascript:countryChange()">
        <option value="0">Select Country</option>
        <option value='US'>United States</option>
        <option value='CA'>Canada</option>
</select>
<label id="stateLabel">State:</label>  
<select name="<portlet:namespace/>State" id="stateId">
</select>

<!--Country and State Change Javascript-->
<script>
function CountryChange() {
    var countryState = [
        [
            'US', [
            ['', 'State/Province'],
            ['AL', 'Alabama'],
            ['AK', 'Alaska'],
            ['AZ', 'Arizona'],
            ['AR', 'Arkansas'],
  ], ],
[
            'CA', [
            ['', 'State/Province'],
            ['AB', 'Alberta'],
            ['BC', 'British Columbia'],
            ['MB', 'Manitoba'],
            ['NB', 'New Brunswick'],
  ]]
   ];

    var countryElement = document.getElementById('countryId');
    var stateElement = document.getElementById('stateId');
    var stateLabelElement = document.getElementById('stateLabel');

if (countryElement && stateElement) {
        var listOfState = [
            ['XX', 'None']
        ];

        var currentCountry = countryElement.options[countryElement.selectedIndex].value;
        for (var i = 0; i < countryState.length; i++) {
            if (currentCountry == countryState[i][0]) {
                listOfState = countryState[i][1];
            }
        }
        if (listOfstate.length < 2) 
            {
            stateElement.style.display = 'none';
            stateLabelElement.style.display = 'none';
            }
    else 
        {
        stateElement.style.display = 'inline';
        stateLabelElement.style.display = 'inline';
        }
        var selectedState;
        for (var i = 0; i < stateElement.length; i++) {
            if (stateElement.options[i].selected === true) {
                selectedState = stateElement.options[i].value;
            }     
        }
        stateElement.options.length = 0;
        for (var i = 0; i < listOfState.length; i++) {
            stateElement.options[i] = new Option(listOfState[i][1], listOfState[i][0]);
            if (listOfState[i][0] == selectedState) {
                stateElement.options[i].selected = true;
            }    
        }      
    }
}
</script>
Share Improve this question asked Feb 1, 2016 at 16:43 TechProTechPro 3311 gold badge11 silver badges29 bronze badges 2
  • I noticed you tagged it with liferay, are you incluiding/using jquery? – jpganz18 Commented Feb 1, 2016 at 16:47
  • Possible duplicate of Dynamically Populating Drop down list from selection of another drop down value – divy3993 Commented Feb 1, 2016 at 16:47
Add a ment  | 

2 Answers 2

Reset to default 2

You had a lot of mis-spellings. Check this out: https://jsfiddle/jj8we58t/1/

I also set the initial display to none for the stateLabel and stateId elements.

<label id="stateLabel" style="display: none">State:</label>  
<select name="<portlet:namespace/>State" style="display: none" id="stateId">

Your code was close, but due to some inconsistencies in variable names, it failed to function. For instance, your onchange event is bound to countryChange, but your function is named CountryChange. It's a good idea to drop your script into some sort of validator like jsHint to analyze why your code isn't working as expected.

with a couple tweaks and those inconsistencies ironed out, it appears to be functioning as expected now HTML:

<select name="<portlet:namespace/>Country" id="countryId" onchange="window.CountryChange()">
  <option value="0">Select Country</option>
  <option value='US'>United States</option>
  <option value='CA'>Canada</option>
</select>
<div id="stateField" style="display:none">
  <label id="stateLabel">State:</label>
  <select name="<portlet:namespace/>State" id="stateId">
  </select>
</div>

JS:

   window.CountryChange = function () {
      var countryState = [
        [
          'US', [
            ['', 'State/Province'],
            ['AL', 'Alabama'],
            ['AK', 'Alaska'],
            ['AZ', 'Arizona'],
            ['AR', 'Arkansas'],
          ],
        ],
        [
          'CA', [
            ['', 'State/Province'],
            ['AB', 'Alberta'],
            ['BC', 'British Columbia'],
            ['MB', 'Manitoba'],
            ['NB', 'New Brunswick'],
          ]
        ]
      ];

      var countryElement = document.getElementById('countryId');
      var stateElement = document.getElementById('stateId');
      var stateLabelElement = document.getElementById('stateLabel');
      var stateFieldElement = document.getElementById('stateField');

      if (countryElement && stateElement) {
        var listOfState = [
          ['XX', 'None']
        ];

        var currentCountry = countryElement.options[countryElement.selectedIndex].value;
        for (var i = 0; i < countryState.length; i++) {
          if (currentCountry == countryState[i][0]) {
            listOfState = countryState[i][1];
          }
        }

        if (listOfState.length < 2) {
          stateFieldElement.style.display = "none";
        } else {
          stateFieldElement.style.display = "inline-block";
        }
        var selectedState;
        for (var i = 0; i < stateElement.length; i++) {
          if (stateElement.options[i].selected === true) {
            selectedState = stateElement.options[i].value;
          }
        }
        stateElement.options.length = 0;
        for (var i = 0; i < listOfState.length; i++) {
          stateElement.options[i] = new Option(listOfState[i][1], listOfState[i][0]);
          if (listOfState[i][0] == selectedState) {
            stateElement.options[i].selected = true;
          }
        }
      }
    }
发布评论

评论列表(0)

  1. 暂无评论