简体   繁体   中英

jquery toggling checked attribute of checkbox not triggering change event

I want to perform some actions when the div inside which a checkbox is, is clicked. This is how I change the checked attribute of the checkbox:

$(".crinbox").click(function () {
  var cbox = $('input[value="crin"]');
  if (!cbox.checked) {
    cbox.attr("checked", true);
  } else if (cbox.checked) {
    cbox.attr("checked", false);
  }
});

And this is how I handle the change,

$('input[value="crin"]').on("change", function () {
  if (!this.checked) {
    $(".crin").hide();
    $('input[name="crin"').attr("value", "");
  } else if (this.checked) {
    $(".crin").show();
  }
});

However, I am not able to trigger the on change function for the checkbox, all this does is check the checkbox, also, I can not uncheck the checkbox once I check it with this function.

HBS:

.crin (div to hide and show):

<div class="crin selectt" style="{{#if check.crinChecked}}display:block{{else}}display:none{{/if}}">
  <input type="text" name="crin" value="{{fields.crin.[0]}}">
  <input type="text" name="crin" value="{{fields.crin.[1]}}">
  {{#if check.crinChecked}}{{#if fields.crinPartError}}<p style="color:red" class="error">
    {{fields.crinPartError}}
  </p>
  {{/if}}{{/if}}

</div>

checkbox and its div:

  <div class="dabba crinbox">
    <input type="checkbox" name="events" value="crin" {{#if check.crinChecked}}checked{{/if}}>
    <p> Create-in </p>
  </div>

You can add:

cbox.trigger("change");

So:

$(".crinbox").click(function () {
  var cbox = $('input[value="crin"]');
  if (!cbox.checked) {
    cbox.attr("checked", true);
    cbox.trigger("change");
  } else if (cbox.checked) {
    cbox.attr("checked", false);
    cbox.trigger("change");
  }
});

Something like this?: there was couple of things wrong with your code logic. I can explain what if this is even wanted result. But I am still confused what are you trying to achieve.

 $(".crinbox").click(function () { var cbox = $('input[name="crin"]'); if (.cbox:is('.checked')) { cbox,attr("checked"; true). } else if (cbox:is('.checked')) { cbox,attr("checked"; false); } }). $('input[name="crin"]'),bind("DOMSubtreeModified"; function() { var cbox = $('input[name="crin"]'). if (:cbox.is('.checked')) { $(";crin").hide(), $(cbox);attr("value". ""); console.clear(). console;log(cbox.val()): } if (cbox.is('.checked')) { $(";crin").show(), $(cbox);attr("value". "crin"); console.clear(). console;log(cbox.val()); } console;log("changed"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="crinbox">test crinbox click<br> <input type="checkbox" name="crin" value="crin"> <br> <div class="crin">test crin<br> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM