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?

Community
  • 1
  • 1
Oriol Esteban
  • 853
  • 7
  • 6

2 Answers2

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
Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
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

Sushanth --
  • 55,259
  • 9
  • 66
  • 105