Javascript/jquery: Show A Hidden Div Based On A Radio Box Select
What I'm doing is building a form, where when you select one answer a bunch of new questions pop up. This is my working code: $('.appliedWorked').click(function(){ if($(this).
Solution 1:
Look at the syntax highlighting in your question. In
if($(this).val()==='"+radioBoxArray[j]+"')
the right-hand side of that test is just the string '"+radioBoxArray[j]+"'
. Remove all those quotes.
if($(this).val() === radioBoxArray[j])
Other cleanup:
Declare the array using array literal notation:
var radioBoxArray = [ "appliedWorkedYes", "workStudyYes", "workHistoryYes", "workWeekEndsYes", "cprYes", "aedYes", "aidYes", "wsiYes", "gaurdYes"];
Save the
radioBoxArray.length
value in a local variable, otherwise it will be recomputed at every iteration. Also save theradioBoxArray[j]
in a local variable (this also more efficient).var len = radioBoxArray.length, radio; for(var j = 0; j < len; j++){ radio = radioBoxArray[j]; // class name $("."+radio).click(function(){ if($(this).val() === radio) $("."+radio+"Hide").show("fast"); else $("."+radio+"Hide").hide("fast"); }); }
Instead of using separate
show()
andhide()
calls, use.toggle(showOrHide)
Final code can be cleaned up like so:
var radioBoxArray = [
"appliedWorkedYes",
"workStudyYes",
"workHistoryYes",
"workWeekEndsYes",
"cprYes",
"aedYes",
"aidYes",
"wsiYes",
"gaurdYes"
],
len = radioBoxArray.length,
radio;
for (var j = 0; j < len; j++) {
radio = radioBoxArray[j];
// class name
$("." + radio).click(function() {
$("." + radio + "Hide").toggle($(this).val() === radio);
});
}
Alternatively, you could use $.each()
:
var radioBoxArray = [
"appliedWorkedYes",
"workStudyYes",
"workHistoryYes",
"workWeekEndsYes",
"cprYes",
"aedYes",
"aidYes",
"wsiYes",
"gaurdYes"
];
$.each(radioBoxArray, function(i, v) {
$("." + v).click(function() {
$("." + v+ "Hide").toggle($(this).val() === v);
});
});
Solution 2:
Try this:
var radioBoxArray = [
"appliedWorked",
"workStudy",
"workHistory",
"workWeekEnds",
"cpr",
"aed",
"aid",
"wsi",
"gaurd"
];
$.map(radioBoxArray, function(cls) {
$('.' + cls).click(function() {
// value boxif($(this).val()===cls + 'Yes')
// show method
$("."+cls+"YesHide").show("fast");
// hide else else $("."+cls+"YesHide").hide("fast");
});
});
Hope it helps!
Solution 3:
if($(this).val()==='"+radioBoxArray[j]+"') is not correct
Try
if($(this).val()=== radioBoxArray[j])
or
if($(this).val()=== String( radioBoxArray[j] ))
Hope that helps
Solution 4:
Change it to:
if($(this).val()==='"'+radioBoxArray[j]+'"')
Post a Comment for "Javascript/jquery: Show A Hidden Div Based On A Radio Box Select"