1

Possible Duplicate:
Adding additional data to select options using jQuery

Is there a way to asign multiple values into a single HTML element other than using the "value" atrribute and play with tokens to split the content?

I would like to do something like this:

<select id="car_model">
  <option value="1" value2="seddan" value3="Volvo">Volvo S60</option>
  <option value="2" value2="compact" value3="Saab">Saab s93</option>
  <option value="3" value2="convertible" value3="Mercedes">Mercedes SLK</option>
  <option value="4" value2="compact" value3="Audi">Audi 3</option>
</select>

How do you retrieve all the values of the selected option using jQuery?

2
  • That's no valid html. Use the data-* attributes instead. Commented Sep 18, 2012 at 20:15
  • Duplicate of stackoverflow.com/q/4564659/41688 Commented Sep 18, 2012 at 21:30

2 Answers 2

1

A couple of things spring to mind. You could, as you intimated, just include all of the data in your value element with some kind of separator like so:

<option value="1,seddan,Volvo">Volvo S60</option>

The other option would be to use data annotations:

<option value="1" data-value2="seddan" data-value3="Volvo">Volvo S60</option>

Which you choose very much depends on how you're going to use it. I can update this answer if you provide some more specifics about how you plan on using the data.

To retrieve the data in the first case, it would look like this:

var values = $('#car_model').val().split(',');
console.log( values[0] );  // prints 1
console.log( values[1] );  // prints "seddan"
console.log( values[2] );  // prints "Volvo"

And in the second case, it would look like this:

console.log( $('#car_model').val() );            // prints 1
console.log( $('#car_model').data('value2') );   // prints "seddan"
console.log( $('#car_model').data('value3') );   // prints "Volvo
Sign up to request clarification or add additional context in comments.

2 Comments

Data annotations seem to be the way to go. I assume the HTML will validate if I do it this way, ins't it?
Data attributes are valid HTML 5; you can read about them here: ejohn.org/blog/html-5-data-attributes
0

You can assign multiple values and retrieve them by using the attr method ..You can try this..

​$('#car_model').on('change', function() {
    var val = $(this).find('option:selected').attr('value');
    var val2 = $(this).find('option:selected').attr('value2');
    var val3 = $(this).find('option:selected').attr('value3');
    alert( 'Value - '+ val + ':: Value2 - '+ val2 + ' :: Value3 - '+ val3 ) 
});​

But I think separating the values with an identifier makes more sense, Maybe by comma or a slash

Check FIDDLE

1 Comment

Thanks for your reply, I voted the other question as valid because it offers 2 solutions which passes HTML validation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.