javascript - Why the input[type=radio]'s defalut value is 'on' instead of ''? - Stack Ov

admin2025-04-19  0

Just show the code:

function show() {
  console.log(document.querySelector('input[type=radio]').value) // 'on'
}
<input type="radio">

<button onclick="show()">Show value</button>

Just show the code:

function show() {
  console.log(document.querySelector('input[type=radio]').value) // 'on'
}
<input type="radio">

<button onclick="show()">Show value</button>

Share Improve this question edited Jan 24, 2019 at 8:44 Jack Bashford 44.2k11 gold badges55 silver badges82 bronze badges asked Jan 24, 2019 at 8:40 chesszhangchesszhang 2011 silver badge8 bronze badges 1
  • 2 That's the default value for radios and checkboxes, you can explicitly set the value in HTML or by JS/jQ. <input type="radio" value='"arbitraryValue"> – zer00ne Commented Jan 24, 2019 at 8:44
Add a ment  | 

4 Answers 4

Reset to default 6

It's the default value for radio and checkbox input. It does not mean that radio button is currently "on". The property you would want for that is checked.

<input type="radio" value="Another Value">
<script>
  console.log(document.querySelector('input[type=radio]').checked)
  console.log(document.querySelector('input[type=radio]').value) // 'on'
</script>

The MDN page for the <input> element states this simply:

The default value for checkboxes and radio buttons is on.

This default makes most sense for checkboxes: if you specify a checkbox named foo, then submitting a form with that box ticked sends the server the string foo=on. This is more convenient than having it send foo=, so the empty string would not be a convenient default.

Since radio buttons are essentially an extension of checkboxes, this default was probably applied to both back when their behaviour was first being designed.

By default, radio buttons (like buttons) has the value on. You need to specify it by giving the tag an value attribute, and very likely a name attribute. e.g.

<input type="radio" name="category" value="1">

The name specifies which group this button belongs to, and value specifies which is the meaning of the selected button, you can read more here.

Because radio input's context as input is that there should always be a selected value.

Its the opposite of checkbox in context, you can opt-out for a value.

Use what's necessary although these defaults can be overridden.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745042208a281611.html

最新回复(0)