Adding additional data to select options using jQuery

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>

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).



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>


// JavaScript using jQuery
       var selected = $(this).find('option:selected');
       var extra ='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:
See this as a working sample using plain JavaScript here:

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.


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.


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

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


HTML/JSP Markup:

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

JQUERY CODE: Event: change

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

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


To store another value in select options:

$("#select").append('<option value="4">another</option>')


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.