What does the value attribute mean for checkboxes in HTML?

When the form is submitted, the data in the value attribute is used as the value of the form input if the checkbox is checked. The default value is "on".

$('form').on('change', update).trigger('change')

function update() {
  var form = $(this)
  form.find('output').text('→ ' + form.serialize())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <input type="checkbox" name="foo">
  <output></output>
</form>

<form>
  <input type="checkbox" name="foo" checked>
  <output></output>
</form>

<form>
  <input type="checkbox" name="foo" value="1" checked>
  <output></output>
</form>

<form>
  <input type="checkbox" name="foo" value="bananas" checked>
  <output></output>
</form>

One reason is to use the ease of working with values ​​in the system.

<input type="checkbox" name="BrandId" value="1">Ford</input>
<input type="checkbox" name="BrandId" value="2">GM</input>
<input type="checkbox" name="BrandId" value="3">Volkswagen</input>

I hope I understand your question right.

The value attribute defines a value which is sent by a POST request (i.e. You have an HTML form submitted to a server). Now the server gets the name (if defined) and the value.

<form method="post" action="urlofserver">
    <input type="checkbox" name="mycheckbox" value="1">Is it worth?</input>
</form>

The server would receive mycheckbox with the value of 1.

in PHP, this POST variable is stored in an array as $_POST['mycheckbox'] which contains 1.


I just wanted to make a comment on Adriano Silva's comment. In order to get what he describes to work you have to add "[]" at the end of the name attribute, so if we take his example the correct syntax should be:

<input type = "checkbox" name="BrandID[]" value="1">Ford</input>
<input type = "checkbox" name="BrandID[]" value="2">GM</input>
<input type="checkbox" name="BrandId[]" value="3">Volkswagen</input>

Then you use something like: $test = $_POST['BrandID']; (Mind no need for [] after BrandID in the php code). Which will give you an array of values, the values in the array are the checkboxes that are ticked's values.

Hope this helps! :)

Tags:

Html