开发者

Get all Select Elements in a Form by referencing $(this) instead of $("form select")

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


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)
}


$("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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜