155

Very simple question I hope.

I have the usual <select> box like this

<select id="select">
    <option value="1">this</option>
    <option value="2">that</option>
    <option value="3">other</option>
</select>

I can get the selected value (by using $("#select").val()) and the selected item's display value (by using $("#select :selected").text().

But how can I store like an additional value in the <option> tag? I would like to be able to do something like <option value="3.1" value2="3.2">other</option> and get the value of the value2 attribute (which would be 3.2 in the example).

Phrogz
  • 296,393
  • 112
  • 651
  • 745
jim smith
  • 1,833
  • 3
  • 16
  • 12
  • you want to add an item to the select box? or you want to be able to select more than one at a time and get the results? – zsalzbank Dec 30 '10 at 17:14
  • no i simply want there to be like a value2="" in the – jim smith Dec 30 '10 at 17:15
  • Your question is not clear (to me, anyhow). What do you mean by "store another value in the select options"? Do you mean you want to add a new option to the select, that would appear to the user when opened? – Phrogz Dec 30 '10 at 17:16
  • you want multiple values for an option? – zsalzbank Dec 30 '10 at 17:19
  • yes exactly, because the select only has one attribute called "value", i need to grab more than 1 value – jim smith Dec 30 '10 at 17:22
  • storing multiple values (plural) inside a single option (singular) defies logic and reason. Select statements are meant to choose one option from many. Maybe you just need to use a different control. You are not giving us the big picture of what you are trying to accomplish, until then, you will only receive shots in the dark and guesses as to what you are trying to do. – jondavidjohn Dec 30 '10 at 17:24
  • 17
    doesn't defy logic or reason, geez. i have a similar question/case so I can compare the values between selects and save the text of one's options onto the other's options while maintaining that select's values/texts, one way it seems possible is through data as the answer below indicates. just because YOU didn't think of it doesn't mean it defies logic and reason. the OP was a decent enough question he just needed to be pointed in right direction, not get a big glass of smug. – user1783229 Sep 14 '13 at 20:58
  • 1
    you can always add any number of extra parameters using data-anything and using .data('anything') wherever you would do a .value otherwise. just swap out anything for value2 or similar to your liking –  Jul 07 '16 at 09:09
  • exactly my question! thanks. – ulab Dec 21 '16 at 16:52

6 Answers6

362

HTML Markup

<select id="select">
  <option value="1" data-foo="dogs">this</option>
  <option value="2" data-foo="cats">that</option>
  <option value="3" data-foo="gerbils">other</option>
</select>

Code

// JavaScript using jQuery
$(function(){
    $('select').change(function(){
       var selected = $(this).find('option:selected');
       var extra = selected.data('foo'); 
       ...
    });
});

// Plain old JavaScript
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');

See this as a working sample using jQuery here: http://jsfiddle.net/GsdCj/1/
See this as a working sample using plain JavaScript here: http://jsfiddle.net/GsdCj/2/

By using data attributes from HTML5 you can add extra data to elements in a syntactically-valid manner that is also easily accessible from jQuery.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • @jimsmith Yes, it will. _(If you find any of these answers useful, you should vote them up. You should also mark one as "accepted" if you found that it best solved your problem.)_ – Phrogz Dec 30 '10 at 17:27
  • 1
    What? No it won't. It will work in all browsers that support HTML5 data attributes. – glomad Dec 30 '10 at 18:46
  • 13
    @ithcy All browsers support (and have for 10+ years) "invalid" attributes in the markup, and getting/setting these through the DOM. HTML5 "data" attributes are just custom attributes with a naming scheme and a new standard that declares them to be legal. – Phrogz Dec 30 '10 at 19:10
  • @Phrogz I know this. It's not a matter of browsers "supporting" invalid attributes, but rather a matter of ignoring them. There is really no other way to write a usable web browser :) However I think it's a stretch to call data attributes "syntactically valid" - it depends on your context. If you have an HTML5 doctype, then yes, they're valid. Otherwise they're not and will cause W3C validation to fail. – glomad Jan 06 '11 at 18:34
  • @ithcy The browsers 'ignore' them insofar as they do nothing special with them, but they do _not_ ignore them insofar as they are fully available to `getAttribute()`. I was responding to your initial claim that my answer would not work in all browsers. I stand by my statement that it will work in 'all' browsers (for a pretty generous definition of 'all' in this case). Show me a browser that supports jQuery but does not work with these data attributes--even with a non-HTML5 doctype--and I will eat my words. – Phrogz Jan 06 '11 at 20:21
  • How would one select based on data attr? eg. data-foo="dogs" is that possible? – Neil Oct 21 '13 at 16:12
  • jQuery variables should be prefixed with $, i.e. var $selected = $(this).find('option:selected'); – Ross Verry Apr 27 '14 at 18:27
  • MVC's html helper methods like Html.DropDownList have no support for this. It accepts only a list of strongly typed SelectListItem objects, which have properties for Value, Text, Selected, Disabled, and Group only. I'm not sure how it would handle being overridden (i.e. whether or not it would propagate the extended values into the options element. – Triynko Nov 16 '15 at 21:09
  • 1
    instead of `selected.getAttribute('data-foo');` you could use `selected.dataset.foo` – Vitaliy Markitanov Aug 11 '20 at 15:45
7

To me, it sounds like you want to create a new attribute? Do you want

<option value="2" value2="somethingElse">...

To do this, you can do

$(your selector).attr('value2', 'the value');

And then to retrieve it, you can use

$(your selector).attr('value2')

It's not going to be valid code, but I guess it does the job.

mikesir87
  • 1,785
  • 1
  • 20
  • 25
  • 1
    The other method is to use $(selector).data('value2', "your value") and $(selector).data('value2') to retrieve... which is still valid. – mikesir87 Dec 30 '10 at 17:22
  • Well, it wouldn't be syntactically valid to have non-standard attributes in the original markup, but a) I've never seen any browser since the days of NS4 have any problem with this, and b) if you can modify the DOM to produce something that is "syntactically invalid", is it really? – Phrogz Dec 30 '10 at 17:35
  • yes, it is really...invalid. why use arbitrary properties when data-* properties have been defined in the html5 standard. – stephenbayer Aug 11 '14 at 21:16
  • 3
    As @stephenbayer mentions... the correct way to do this now is using the html5 supported data-* properties. Those properties weren't really around/in heavy use when originally answered back in 2010 :) – mikesir87 Mar 07 '17 at 14:37
2

I made two examples from what I think your question might be:

http://jsfiddle.net/grdn4/

Check this out for storing additional values. It uses data attributes to store the other value:

http://jsfiddle.net/27qJP/1/

zsalzbank
  • 9,685
  • 1
  • 26
  • 39
0

HTML

<Select id="SDistrict" class="form-control">
    <option value="1" data-color="yellow" > Mango </option>
</select>

JS when initialized

   $('#SDistrict').selectize({
        create: false,
        sortField: 'text',
        onInitialize: function() {
            var s = this;
            this.revertSettings.$children.each(function() {
                $.extend(s.options[this.value], $(this).data());
            });
        },
        onChange: function(value) {
            var option = this.options[value];
            alert(option.text + ' color is ' + option.color);
        }
    });

You can access data attribute of option tag with option.[data-attribute]

JS Fiddle : https://jsfiddle.net/shashank_p/9cqoaeyt/3/

Shashank Pujari
  • 159
  • 1
  • 7
-1

HTML/JSP Markup:

<form:option 
data-libelle="${compte.libelleCompte}" 
data-raison="${compte.libelleSociale}"   data-rib="${compte.numeroCompte}"                              <c:out value="${compte.libelleCompte} *MAD*"/>
</form:option>

JQUERY CODE: Event: change

var $this = $(this);
var $selectedOption = $this.find('option:selected');
var libelle = $selectedOption.data('libelle');

To have a element libelle.val() or libelle.text()

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Fadid
  • 1,250
  • 15
  • 16
-4

To store another value in select options:

$("#select").append('<option value="4">another</option>')
Kyle
  • 915
  • 8
  • 18
  • 34