javascript - jQuery if (x == y) not working -
so, have faux checkboxes (so style them) work jquery act checked or not checked. there number of faux checkboxes in document, , each 1 have click function:
var productinterest = []; productinterest[0] = false; productinterest[1] = false; productinterest[2] = false; // here 1 function of three: $('#productone').click(function() { if (productinterest[0] == false) { $(this).addclass("checkboxchecked"); productinterest[0] = true; } else { $(this).removeclass("checkboxchecked"); productinterest[0] = false; } });
the problem seems there error in if statement, because check, not uncheck. in other words add class, variable won't change still thinks checked. have ideas? help.
update: so, need show code because works in way supplied (thanks commenters helping me realize that)... not in way being used on site. below please find code in entirety.
everything needs happen in 1 function, because ui , data each checkbox need updated @ once. here complete function:
$('input[name=silkinterest]').click(function() { // have same name var silkinterest = []; silkinterest[0] = false; silkinterest[1] = false; silkinterest[2] = false; if ($(this).is('#silksilk')) { // function stops working because .is() if (silkinterest[0] == false) { $(this).addclass("checkboxchecked"); silkinterest[0] = true; } else { $(this).removeclass("checkboxchecked"); silkinterest[0] = false; } alert(silkinterest[0]); } if ($(this).is('#silkalmond')) { if (silkinterest[1] == false) { $(this).addclass("checkboxchecked"); silkinterest[1] = true; } else { $(this).removeclass("checkboxchecked"); silkinterest[1] = false; } } if ($(this).is('#silkcoconut')) { if (silkinterest[2] == false) { $(this).addclass("checkboxchecked"); silkinterest[2] = true; } else { $(this).removeclass("checkboxchecked"); silkinterest[2] = false; } } var silkintereststring = silkinterest.tostring(); $('input[name=silkinterestanswer]').val(silkintereststring); // last bit puts code hidden field can capture php. });
i can't spot problem in code, can use class you're adding in place of productinterest
array. lets condense code down single:
// condense productone, producttwo, etc... $('[id^="product"]').click(function() { // condense addclass, removeclass $(this).toggleclass('checkboxchecked'); });
and check if 1 of them checked:
if ($('#productone').hasclass('checkboxchecked')) {...}
this'll make sure ui synced "data", if there's other code that's interfering you'll able spot it.
Comments
Post a Comment