2

I want to toggle the checkbox on click of button.

Here is my jQuery

$("#choose_address2").on("click", function () { 
   console.log("click!!! address2");
   var $checkbox = $(this).find(':checkbox');
   var checkBoxes = $("input[name=checkbox]]");
   checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});

Here is my Input

<span id="choose_address2" class="btn btn-info">
<i class="fa fa-plus-circle"></i>เพิ่มที่อยู่
<input type="checkbox" name="choose_address" {{#if customer.addresses}}checked{{/if}} id="choose_address1" hidden>
</input></span>

By default the button is checked. however when i click the span with id choose_address2 I want to change the state. Any suggestions will be highly appreciated.

1
  • try this: $checkbox.prop("checked", !$checkbox.prop("checked")); Commented Feb 2, 2016 at 11:46

5 Answers 5

7

Try This

$("#choose_address2").on("click", function () { 
   console.log("click!!! address2");
   var $checkbox = $(this).find(':checkbox');
   var checkBoxes = $("input[type='checkbox']");
   if(checkBoxes.prop("checked")==true)
     checkBoxes.prop("checked", false); 
   else
     checkBoxes.prop("checked", true)
});

Or This also work

$("#choose_address2").on("click", function () { 
   console.log("click!!! address2");
   var $checkbox = $(this).find(':checkbox');
   var checkBoxes = $("input[type='checkbox']");
   (checkBoxes.prop("checked")==true)?checkBoxes.prop("checked", false):checkBoxes.prop("checked", true);       

});
Sign up to request clarification or add additional context in comments.

Comments

3
$("#choose_address2").on("click", function() {
     var $checkbox = $(this).find(':checkbox');
     $checkbox.prop("checked", !$checkbox.prop("checked"));
});

Comments

1

Heres an example

HTML

<input type="checkbox" class="toggle" checked>
<input type="checkbox" class="toggle">
<button id="choose_address2">
 Toggle checkbox
</button>

JQ

$('#choose_address2').click(function(){
   $('.toggle').each(function(){
     $(this).prop('checked', !$(this)[0].checked);
  })
})

Demo http://jsfiddle.net/mPstq/94/

Comments

1

Easiest way to tackle this:

$checkbox.prop( 'checked', ! $checkbox.is( ':checked' ) );

Comments

0

Thank you all for you suggestion..

This did the trick for me :

$("#choose_address2").click(function(){
   var checkBox = $("#choose_address1");
   console.log("click!!! address2");
   checkBox.trigger('click');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.