Being new to javascript I have come across an odd issue. I have an array of elements and a variable, I want to compare that variable to all array elements and do something if they match .
Here is the snippet of code:
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
if(selected_country == country_arr[i]){
option_str.options[i].selected = true;
}
}
The array itself is an array of strings:
var country_arr = new Array("Republic of Ireland", "Northern Ireland");
For whatever reason this does not enter the if statement but oddly enough when i replace:
if(selected_country == country_arr[i])
with:
if(selected_country == "Republic of Ireland")
...it does and works perfectly.
Am I comparing the two elements incorrectly? Any help would be greatly appreciated.
UPDATE - FULL .js FILE:
Full External .js File:
//Create a new array, to contain the list of countries available.
var country_arr = new Array("Republic of Ireland", "Northern Ireland");
//Create a new array to hold a list of counties depending on country selection.
var s_a = new Array();
s_a[0]="";
s_a[1]="Carlow|Cavan|Clare|Cork|Donegal|Dublin|Galway|Kerry|Kildare|Kilkenny|Laois|Leitrim|Limerick|Longford|Louth|Mayo|Meath|Monaghan|Offaly|Roscommon|Sligo|Tipperary|Waterford|Westmeath|Wexford|Wicklow";
s_a[2]="Antrim|Armagh|Down|Dungannon|Derry|Tyrone";
function print_country(country_id, selected_country){
//Given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Select Country','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
if(selected_country == country_arr[i]){
option_str.options[i].selected = true;
print_county('county',i);
}
}
}
function print_county(state_id, state_index){
var option_str = document.getElementById(state_id);
option_str.length=0; // Fixed by Julian Woods
option_str.options[0] = new Option('Select County','');
option_str.selectedIndex = 0;
var state_arr = s_a[state_index].split("|");
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
The function is called and the variable selected_country is set via a php file using:
<script language="javascript">
var selected = <?php echo json_encode($g_country); ?>;
print_country("country", selected);
</script>
selected_countryset? Please post the complete code and its invocation