开发者

Why do I need to give my options a value attribute in my dropdown? JQuery related

开发者 https://www.devze.com 2022-12-29 13:48 出处:网络
So far in my web developing experiences, I\'ve noticed that almost all web developers/designers choose to give their options in a select a value like so:

So far in my web developing experiences, I've noticed that almost all web developers/designers choose to give their options in a select a value like so:

<select name="foo">
    <option value="bar">BarCheese</option>
    // etc.
    // etc.
</select>

Is this because it is best practice to do so? I ask this because I have done a lot of work with jQuery and dropdown's lately, and sometimes I get really annoyed when I have to check something like:

$('select[name=foo]').val() == "bar"); 

To me, many times that seems less clear than just being able to check the val() against BarCheese. So why is it that m开发者_JS百科ost web developers/designers specify a value paramater instead of just letting the options actual value be its value?

And yes, if the option has a value attribute I know I can do something like this:

$('select[name=foo] option:contains("BarCheese")').attr('selected', 'selected');

But I would still really like to know why this is done.

Thanks!!


Sometimes the values are not the same as the labels. Example: my application works both in French and Dutch. I code the values in English and use those to check in my code, but the user sees the option in his own language.

Other than that, you can get away with putting BarCheese as option, or just leaving it. Just remember that if the label one day changes (Manager/client wants it, application gets translated, ...) you'll have to use the old label as value.

The W3-org specification notes the 'value' attribute for OPTION as IMPLIED (defaults to element content), so it is syntactically allowed to omit it.


To me, many times that seems less clear than just being able to check the val() against BarCheese. So why is it that most web developers/designers specify a value paramater instead of just letting the options actual value be its value?

Mostly value is the same as the visible part (BarCheese) in drop down but this is not the case always. Specifying a value turns out to be useful when you want to retrieve the value of the drop down using a server-side language when the form is submitted. You come to know which option a user selected. Also, this makes your markup semantic.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号