Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why <select>'s value attribute doesn't set <select>'s value property?

Supposing a select like

<select name="myselect" id="myselect">
  <option value="a">A</option>
  <option value="b">B</option>
</select>

I can set the selected option changing it's value property:

document.getElementById('myselect').value = 'b';

But I can't do it with value attribute, so the following doesn't work:

<?php
  $myselectValue = $_GET['myselect'] ?: 'a';
  // Do something with $myselectValue
?>
<select name="myselect" id="myselect" value="<?php echo $myselectValue; ?>">
  <option value="a">A</option>
  <option value="b">B</option>
</select>

and, instead, I must write uglier and less clean server-side code.

I think it makes more sense to choose the selected option with <select>'s value attribute instead of <option>'s selected one.

Why did w3c think that <option value="x" selected> is better than <select value="x">? Maybe is there any advantage I don't see?

like image 608
Oriol Avatar asked Mar 24 '26 02:03

Oriol


1 Answers

There's no telling what they were thinking, but there are a couple of cases where value may not make sense:

  • The value is invalid
  • With <select multiple>

Also keep in mind that the property is different from the attribute.

Semantically it makes more sense to have the list of available options (through <option>) and the select attribute indicating the option (or options) that is actually selected rather than having to reconcile this with an attribute value.

like image 185
Explosion Pills Avatar answered Mar 26 '26 01:03

Explosion Pills