views:

2883

answers:

3

Given a select with multiple option's in JQuery.

$select = $("<select></select>");
$select.append("<option>Jason</option>") //Key = 1
       .append("<option>John</option>") //Key = 32
       .append("<option>Paul</option>") //Key = 423

How should the key be stored and retrieved?

The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios).

Thanks

and in the spirit of TMTOWTDI.

$option = $("<option></option>");
$select = $("<select></select>");
$select.addOption = function(value,text){
    $(this).append($("<option/>").val(value).text(text));
};

$select.append($option.val(1).text("Jason").clone())
       .append("<option value=32>John</option>")
       .append($("<option/>").val(423).text("Paul"))
       .addOption("321","Lenny");

@Juan and Lucas Thanks!

+2  A: 

The HTML tag has an attribute called "value", where you can store your key.

e.g.:

<option value=1>Jason</option>

I don't know how this will play with jQuery (I don't use it), but I hope this is helpful nonetheless.

Lucas Richter
+6  A: 

Like lucas said the value attribute is what you need. Using your code it would look something like this ( I added an id attribute to the select to make it fit ):

$select = $('<select id="mySelect"></select>');
$select.append('<option value="1">Jason</option>') //Key = 1
   .append('<option value="32">John</option>') //Key = 32
   .append('<option value="423">Paul</option>') //Key = 423

jQuery lets you get the value using the val() method. Using it on the select tag you get the current selected option's value.

$( '#mySelect' ).val(); //Gets the value for the current selected option

$( '#mySelect > option' ).each( function( index, option ) {
    option.val(); //The value for each individual option
} );

Just in case, the .each method loops throught every element the query matched.

Juan
+1  A: 

If you are using HTML5, you can use a custom data attribute. It would look like this:

$select = $("<select></select>");
$select.append("<option data-key=\"1\">Jason</option>") //Key = 1
   .append("<option data-key=\"32\">John</option>") //Key = 32
   .append("<option data-key=\"423\">Paul</option>") //Key = 423

Then to get the selected key you could do:

var key = $('select option:selected').attr('data-key');

Or if you are using XHTML, then you can create a custom namespace.

Since you say the keys can repeat, using the value attribute is probably not an option since then you wouldn't be able to tell which of the different options with the same value was selected on the form post.

Ricky