Country and State selection using html and Javascript

左心房为你撑大大i 提交于 2019-12-24 13:52:52

问题


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>

回答1:


You had a lot of mis-spellings. Check this out: https://jsfiddle.net/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">



回答2:


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;
          }
        }
      }
    }


来源:https://stackoverflow.com/questions/35135722/country-and-state-selection-using-html-and-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!