Country And State Selection Using Html And Javascript
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
Solution 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">
Solution 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:
<selectname="<portlet:namespace/>Country"id="countryId"onchange="window.CountryChange()"><optionvalue="0">Select Country</option><optionvalue='US'>United States</option><optionvalue='CA'>Canada</option></select><divid="stateField"style="display:none"><labelid="stateLabel">State:</label><selectname="<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] = newOption(listOfState[i][1], listOfState[i][0]);
if (listOfState[i][0] == selectedState) {
stateElement.options[i].selected = true;
}
}
}
}
Post a Comment for "Country And State Selection Using Html And Javascript"