Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML: In a select, is it required that the value attribute of each option be unique?

Tags:

Are the any requirements in the HTML spec that say the values of the options in a select must be unique?

My question is about the validity of duplicate values. Ignore all the impracticalities in the following code block, is the select valid?

<select id="produce" multiple>
    <option value="2.00">Apple</option>
    <option value="1.50">Banana</option>
    <option value="1.50">Carrot</option>
</select>

<input id="total" type="text">

<script>
    $('#produce').on('change',function(e) {
        var sum = 0;
        $('#produce option:selected').each(function() {
            sum += parseFloat($(this).val());
        });
        $('#total').val(sum.toFixed(2));
    });
</script>
like image 532
Walter Stabosz Avatar asked Oct 31 '13 18:10

Walter Stabosz


2 Answers

The value of the option in the select list doesn’t affect the validity of the select element.

One thing that you need to keep in mind is that the id of an element must be unique for consistency in accessing that element properly. If duplicate ids exist for multiple elements the last instance of that id will be selected. You definitely need not worry about the duplication of values of the options in the select list.

This may even be required too, e.g. the following:

<select>
    <option value="fruit">mango</option>
    <option value="flower">rose</option>
    <option value="fruit">pineapple</option>
    <option value="flower">lotus</option>
    <option value="flower">lily</option>
</select>

Now if the user selects any of rose, lotus, or lily, the value of the select element will be flower, and in case either of mango and pineapple is selected, the value of the select element will be fruit. So it’s perfectly OK, and you may need this sometimes.

like image 65
Rajesh Paul Avatar answered Oct 06 '22 01:10

Rajesh Paul


No, there is no such requirement. All HTML specifications define the value attribute simply as having a text (CDATA) value without imposing any restrictions.

This is, of course, just the formal side. It is difficult to imagine a situation where it would make sense to have two option elements in the same select element with the same value attribute. It is formally valid, but if you think you need it, you have probably misanalyzed something.

like image 20
Jukka K. Korpela Avatar answered Oct 06 '22 00:10

Jukka K. Korpela