javascript - Any way to create a "state" listener instead of an "event" listener? -
i know can add click
or change
listener on checkbox. handler changes disabled
prop
of button true
when checkbox unchecked. that's easy.
but rather having event-driven, there way have "state" driven?
if "state" of checkbox unchecked, "state" of button disabled. doesn't matter kind of event triggers state change. if checkbox in 1 state, button in corresponding state. that's it.
here's example of standard event-driven code checkout button should disabled long terms , conditions checkbox unchecked.
$('input[name="terms-and-conditons"]').change(function(e, tmpl){ if(e.target.checked === true){ $('#checkout-button').prop("disabled", false); } else { $('#checkout-button').prop("disabled", true); }; });
unfortunately doesn't take account initial states, since requires event happen else happen. on page load, if checkbox unchecked, button still enabled, unless care taken remember set initial state of button disabled:
// setting initial state $('#checkout-button').prop("disabled", true); $('input[name="terms-and-conditons"]').prop("checked", false); $('input[name="terms-and-conditons"]').change(function(e, tmpl){ if(e.target.checked === true){ $('#checkout-button').prop("disabled", false); } else { $('#checkout-button').prop("disabled", true); }; });
i'm wondering if there way create "state listener." no matter event happens (even if there isn't event, default value on pageload), button state in lockstep checkbox state. changed via click, space key press, change event, editing html directly in chrome console, or might load in kind of state. point things are. , state of things can automatically change state of other things.
you can use trigger
force event handler run on page load. can change button state using checkbox state.
// setting initial state $('#checkout-button').prop("disabled", true); $('input[name="terms-and-conditons"]').on('change', function() { $('#checkout-button').prop("disabled", !$(this).is(':checked')); }).trigger('change'); // ^^^^^^^^^^^^^^^^^
Comments
Post a Comment