Metalcoder
Metalcoder

Reputation: 2292

What does the value attribute mean for checkboxes in HTML?

Suppose this checkbox snippet:

<input type="checkbox" value="1">Is it worth?</input>

Is there any reason to statically define the value attribute of checkboxes in HTML? What does it mean?

Upvotes: 36

Views: 55499

Answers (4)

Alf Eaton
Alf Eaton

Reputation: 5483

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".

See MDN for more information.

$('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>

Upvotes: 4

user1116033
user1116033

Reputation: 494

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.

Upvotes: 32

AFOC
AFOC

Reputation: 854

For the sake of a quick glance answer, from MDN

when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the value attribute

It can be confusing because seeing something like <input type='checkbox' name='activated' value='1'> might lead one to believe that the 1 means true and it will be treated as though it is checked, which is false. The checked attribute itself also only determines if the checkbox should be checked by default on page load, not whether it is currently checked and thus going to be submitted.

Upvotes: 2

Adriano Silva
Adriano Silva

Reputation: 2576

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>

Upvotes: 7

Related Questions