views:

40

answers:

4

hello,

i have combobox (in fact, several of them), with elements that are added dynamicly.

using jQuery, i don't know how to implement function that will return id of item i selected in combo...

i know that it have to be something using .live(), something like

$(".foo").live("change", function() {
do something;
});

... but i don't know how to implement it here.

tnx in adv!

+1  A: 

Use the :selected selector on child elements of the select element (a.k.a. options)

$(".foo").live("change").function(){ 
    var val = $(".foo").find(":selected").val();
    // pass val to some other method for work
});

http://api.jquery.com/selected-selector/

hunter
+1  A: 

Are you looking for something like this?

$(".foo").live("change", function() {
  $(this).val(); // value of the changed item
});
Daniel Mendel
+1  A: 
$(".foo").live("change", function() {
   alert($(this).attr("id")); // Id of the element
});
John Hartsock
I think this is the answer if he wanted the id of the select element but I think if you read carefully he's looking for the value of the selected option
hunter
+1  A: 

You can use $(this).val() to find the value of the element that fired the event.

It seems others have beat me to it. Mine is the same as @John and @Daniel.

Here is a jsfiddle to test it out jsfiddle.

One thing to note is that the live does not support the change method in all browsers (such as IE 6 through 8).

One way around this is to use the delegate method, which I have demonstrated here

It would look something like:

$(parentElement).delegate(selector, 'change', function() {
    //do something interesting here
    //$(this).val() still works.
});
partkyle