views:

73

answers:

2

Hi Guys

I'm currently getting all the Select elements that exist in a form with the following:

$("form").submit(function(event)
{
    // gather data
    var data = GetSelectData($("form select"));

    // do submit
    $.post($(this).attr("action"), data, ..etc)
});

Instead of passing in $("form select"), is there a way I can say something like

$(this).children('select') // this doesn't work, btw

to get all the select elements that exist within the context of the form the submit event is executing for?

This will allow me to reduce my code to the following, moving all the functionality into a common function:

$("form").submit(function(event)
{
    GatherDataAndSubmit($(this));
});

function GatherDataAndSubmit(obj)
{
    var data = GetSelectData(obj.children('select'));

    $.post(obj.attr("action"), data, ..etc)
}

Thanks

Dave

+4  A: 

Use .find()

Try

var data = GetSelectData(obj.find('select'));

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

$("form").submit(function(event)
{
    GatherDataAndSubmit($(this));
});

function GatherDataAndSubmit(obj)
{
    var data = GetSelectData(obj.find('select'));

    $.post(obj.attr("action"), data, ..etc)
}
rahul
+1  A: 
$("form").submit(function(event) {
    // gather data
    var data = GetSelectData($("select", this));

    // ...
});

Always specify the second argument when possible, this specifies the context/scope in which the selector will actually search.

Alex