views:

572

answers:

2

I've made a jquery/ajax function that updates #courses, sending #fos's .val() and .text(), specifically of the one that is selected, like so:

$('#selling #fos').change(function() {
    $.post('/ajax/courses',
        {
            fos_id: $('#selling #fos').val(),
            name: $('#selling #fos :selected').text()
        },
    function(data) {
        $('#selling #courses').html(data);
    });
});

How do I extend this function so that it uses 'this', allowing me to reuse this function multiple times on the same page? I'm caught because you can't use name: $(this + ' :selected').text().

+4  A: 

This should work:

$("#"+$(this).attr("id")+" :selected")

it's not pretty but it does the trick :)

but i dont think this will work:

$(this).find(":selected").text()
Stefanvds
Using attr("id") is no different in efficiency to specifying the id directly into the code.
Mouhannad
The example with `find` is fine. Much better than messing around with IDs (will fail if `this` doesn't have an ID, or has an ID with `.` or `:` characters in)
bobince
Ahh I didn't see that Brett had a space before ":selected" which means he is looking for a child.. then yes find() will work fine. I changed my vote!!
Mouhannad
The second one is find, and in fact should be the correct answer.
Yi Jiang
+1  A: 

I think what you are looking for is .filter()

name: $(this).filter(':selected').text()

It will return empty string if it's not selected

Good luck!

Edit:

I didn't see that Brett had a space before ":selected" which means he is looking for a child. Stefanvds suggestion to use find() will work fine. filter() checks if the current dom is ":selected" while find() is going to look for the children on all levels. You could also use .children() if you know that the selected dom you are looking for is a direct child of "this" as it is a lot more efficient since you are only looking for one level of children.

name: $(this).children(':selected').text()
Mouhannad