I have a set of arrays each with a series of objects inside. And I want to select the array depending on which select option is chosen.
<select id="job" name="job">
<option value="job_1">job_1</option>
<option value="job_2">job_2</option>
<option value="job_3">job_3</option>
</select>
I have a function that selects the option on change. I have tried using an if statement to select the option that matches the option select but it keeps returning only the first array.
var selectedValue;
$("#job").change(function() {
selectedValue = $("#job option:selected").val();
return selectedValue;
}).change();
if(selectedValue == "job_1"){
var country_data = [
{"country_id":1,"country":"Luxembourg","local_wage":"407","wage":"489","exchange":"0.98"},
{"country_id":2,"country":"Norway","local_wage":"3200","wage":"378","exchange":"9.57"},
{"country_id":3,"country":"Austria","local_wage":"290","wage":"337","exchange":"0.87"}
];
}
else if(selectedValue == "job_2"){
var country_data = [
{"country_id":1,"country":"Luxembourg","local_wage":"874","wage":"654","exchange":"0.24"},
{"country_id":2,"country":"Norway","local_wage":"741","wage":"365","exchange":"4.77"},
{"country_id":3,"country":"Austria","local_wage":"854","wage":"634","exchange":"0.43"}
];
}
else if(selectedValue == "job_3") {
var country_data = [
{"country_id":1,"country":"Luxembourg","local_wage":"854","wage":"985","exchange":"0.25"},
{"country_id":2,"country":"Norway","local_wage":"645","wage":"874","exchange":"5.55"},
{"country_id":3,"country":"Austria","local_wage":"201","wage":"256","exchange":"0.78"}
];
}
Any suggestions would great.
Presently that if statement only runs once on page load and at that time the only selected item is the job_1.
Your if statement needs to run when the select box change event is running.
I created a fiddle with a short example based on your code which also includes printing the current object to show the chosen data: http://jsfiddle.net/6a1ux1ot/6/
Short preview:
$("#job").change(function () {
selectedValue = $("#job option:selected").val();
if (selectedValue == "job_1") {
...
}
}).change();
This is an updated fiddle http://jsfiddle.net/u1z7c696/1/ that works like you want. The problem was that your fiddle didn't include my fix for your first issue. You never ran your if statement in your change event handler so the country_data variable never got updated. There were also a few other js-errors I fixed with regards to declaration of variables.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments