Saturday, 15 May 2010

javascript - How to nest a click function inside a change function with jquery? -



javascript - How to nest a click function inside a change function with jquery? -

i have select dropdown 2 options: yes / no (actually three: there "select option" no value). there chekboxes handle variables (when checked variables added global variable (called tot), when unckecked subtracted). i'd have 2 different behaviors of checkboxes depending on if dropdown alternative yes or no. wrote this, think i'm misunderstanding/mistaking something, because doesn't work (it works when it's not nested within alter select function).

<select name="container" id="container"> <option id="none" value="" >select option</option> <option id="no" value="no" >no</option> <option id="yes" value="yes" >yes</option> </select>

and here's javascript (with jquery library)

var tot = 0; $(document).ready(function () { $("#container").change(function () { var sel = $(this).find(":selected").attr("id") if (sel == "no" || sel == "none") { $("#in-category-1").click(function () { if ($('#in-category-1').is(':checked')) { if (tot < 60) { tot = tot + 2.5; } else if (tot >= 60) { alert('stop!'); $('#in-category-1').attr('checked', false); } } else if (tot > 0) { tot = tot - 2.5; } functionblablabla(); }); if (sel == "yes") { $("#in-category-1").click(function () { if ($('#in-category-1').is(':checked')) { if (tot < 50) { tot = tot + 2.5; } else if (tot >= 50) { alert('stop!'); $('#in-category-1').attr('checked', false); } } else if (tot > 0) { tot = tot - 2.5; } functionblablabla2(); }); }); });

something should happen when options selected default on page load (options stored in database), if no selected same thing should happen

if (($('#no').prop('defaultselected')) || ($('#none').prop('defaultselected')) ) { $("#in-category-1").click(function () { //same stuff alter select no or select none }); } if ($('#yes').prop('defaultselected')) { $("#in-category-1").click(function () { //same stuff alter select yes }); }

what doing wrong?

some points can better:

brackets looks 'if yes' should part of big if block missing closing ones don't create global vars put 'tod' var in dom ready function

detach previous click events (otherwise events sume if options changed more once)

$("#in-category-1").off("click");

get selected value shortcut

$(this).val();

fiddle: http://jsfiddle.net/kmybv/

javascript jquery nested

No comments:

Post a Comment