Checkbox true / false

I have a form with a checkbox, and I want it to be validated after the form is submitted, when it returns to the same view with an error. I heard that the value attribute can help me set the checkbox, so I'm trying to set it to true / false. In any case, the input value remains "false" even if I click on it. What exactly is going on? I thought the value would be true / false after clicking on the checkbox

<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false"> <script> $("#checkbox1").is(':checked', function(){ $("#checkbox1").attr('value', 'true'); }); </script> 
+13
source share
7 answers

If I understand the question, do you want to change the value of the checkbox depending on whether it is checked or not.

Here is one solution:

 $('#checkbox-value').text($('#checkbox1').val()); $("#checkbox1").on('change', function() { if ($(this).is(':checked')) { $(this).attr('value', 'true'); } else { $(this).attr('value', 'false'); } $('#checkbox-value').text($('#checkbox1').val()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false"> <div id="checkbox-value"></div> 
+22
source

Use Checked = true

 $("#checkbox1").prop('checked', true); 

Note. I do not know if you want to enable the onclick / onchange event in the checkbox. is(":checked", function(){}) is incorrect in the question.

+5
source

try it

 $("#checkbox1").is(':checked', function(){ $("#checkbox1").prop('checked', true); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false"> 
+2
source

Checkboxes in JS can be very strange. It is best to check for the checked attribute. (I had older versions of jQuery returning true, even if the checked parameter was set to false.) After you determine that something is checked, you can get the value from the value attribute.

+1
source

jQuery.is() does not have a signature for .is('selector', function) .

I think you want to do something like this:

  if($("#checkbox1").is(':checked')){ $("#checkbox1").attr('value', 'true'); } 
+1
source

I am going to post this answer under the following assumptions. 1) You (un)selected the checkbox on the first page and submitted the form. 2) Your building the second form and you setting the value="" true/false depending on if the previous one was checked. 3) You want the checkbox to reflect if it was checked or not before.

If so, you can do something like:

 var $checkbox1 = $('#checkbox1'); $checkbox1.prop('checked', $checkbox1.val() === 'true'); 
+1
source

The solution helped me, thanks Boyan Petkowski

0
source

All Articles