开发者

How to reference input elements within a specific scope when there are multiple input elements of same kind?

How do I select data for input elements within a specific scope? I have the same form multiple times (class "foo-form), and want to ensure I get the values for the hidden inputs within the scope of the form being submitted. Is the scope "this" implied? If not, what is the syntax for selecting input class "foo-text" within the scope of this? Feel free to point me to examples in the jquery docs - I could not find what I was looking for.

$('.foo-form').submit(开发者_运维问答function() {
    // Store a reference to this form
    var $thisForm = $(this);

});


<form class="foo-form">
<input type="hidden" class="foo-text"/>
<input type="submit" class="button" />
</form>
<form class="foo-form">
<input type="hidden" class="foo-text"/>
<input type="submit" class="button" />
</form>
<form class="foo-form">
<input type="hidden" class="foo-text"/>
<input type="submit" class="button" /> // user clicks this submit button
</form>


If you want all of the hidden input elements from the current form, then do the following:

$('.foo-form').submit(function() {
    var $hiddenInputs = $('input[type="hidden"]', this);
});

That would get you a list of potentially many hidden inputs within the form that was just submitted. If you want to get specifically the one with the class foo-text then we can be that specific, and get its value:

$('.foo-form').submit(function() {
    var hiddenValue = $('input.foo-text', this).val();
});

Also remember that if you want to prevent the form from submitting normally (causing a page change) the you must return false at the end of the callback function you are defining:

$('.foo-form').submit(function() {
    ...

    return false;
});


Using the $(this) selector will work with the current class that is selected. Therefore, if you were to do an alert($('.foo-text', this).val()); you should get the value of the hidden input type for the specific form you hit Submit on. Of course, there needs to be a value of the hidden form field for you to get anything back.


It's worth noting that, while:

$('input[type="hidden"]',this);

works, it's a little faster (because of the way jQuery implements context searching) to use:

$(this).find('input[type="hidden"]');

Not to mention a little more concise (though not, necessarily, more efficient) to use:

$(this).find('input:hidden');

jQuery API docs for :hidden pseudo-selector.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜