Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox value true/false

I have a form with checkbox and I want to keep it checked after submitting the form when it goes back to the same view with an error. I heard that the value attribute can help me to make the checkbox be checked so im trying to set it to true/false. Anyway, the input value stays "false" even if I click it. What happens exactly? I thought the value goes true/false after clicking the checkbox

<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false">        <script>           $("#checkbox1").is(':checked', function(){               $("#checkbox1").attr('value', 'true');           });       </script> 
like image 841
divHelper11 Avatar asked May 06 '16 12:05

divHelper11


People also ask

How can I make a checkbox value true?

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.

How do you check if a checkbox is true or false?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

Does checkbox return true or false?

The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.


1 Answers

If I understand the question, you want to change the value of the checkbox depending if 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>
like image 170
Bojan Petkovski Avatar answered Oct 08 '22 11:10

Bojan Petkovski