jQuery获取所有表单元素:input,textarea和选择 [英] jquery get all form elements: input, textarea & select

查看:153
本文介绍了jQuery获取所有表单元素:input,textarea和选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jquery中是否有一种简便的方法(不将它们全部单独列出)来选择所有表单元素和仅表单元素.

Is there an easy way (without listing them all separately) in jquery to select all form elements and only form elements.

我不能使用children()等,因为表单包含其他HTML.

I can't use children() etc because the form contains other HTML.

例如:

$("form").each(function(){
    $(this, "input, textarea, select");
});

推荐答案

编辑:如注释中所指出( Brock Hensley ),使用.find获取孩子

As pointed out in comments (Mario Awad & Brock Hensley), use .find to get the children

$("form").each(function(){
    $(this).find(':input') //<-- Should return all input elements in that specific form.
});

表单也有一个元素集合,有时这与子元素有所不同,例如,当表单标签位于表中且未关闭时.

forms also have an elements collection, sometimes this differs from children such as when the form tag is in a table and is not closed.

var summary = [];
$('form').each(function () {
    summary.push('Form ' + this.id + ' has ' + $(this).find(':input').length + ' child(ren).');
    summary.push('Form ' + this.id + ' has ' + this.elements.length + ' form element(s).');
});

$('#results').html(summary.join('<br />'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="A" style="display: none;">
    <input type="text" />
    <button>Submit</button>
</form>
<form id="B" style="display: none;">
    <select><option>A</option></select>
    <button>Submit</button>
</form>

<table bgcolor="white" cellpadding="12" border="1" style="display: none;">
<tr><td colspan="2"><center><h1><i><b>Login
Area</b></i></h1></center></td></tr>
<tr><td><h1><i><b>UserID:</b></i></h1></td><td><form id="login" name="login" method="post"><input
name="id" type="text"></td></tr>
<tr><td><h1><i><b>Password:</b></i></h1></td><td><input name="pass"
type="password"></td></tr>
<tr><td><center><input type="button" value="Login"
onClick="pasuser(this.form)"></center></td><td><center><br /><input
type="Reset"></form></td></tr></table></center>
<div id="results"></div>

您可能想要的是 :input 选择器

May be :input selector is what you want

$("form").each(function(){ $(':input',this)//<-应该以该特定形式返回所有输入元素. });

$("form").each(function(){ $(':input', this)//<-- Should return all input elements in that specific form. });

文档中指出的

要在使用:input选择元素时获得最佳性能,请首先使用纯CSS选择器选择元素,然后使用.filter(:input").

To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

您可以像下面那样使用

$("form").each(function(){
    $(this).filter(':input') //<-- Should return all input elements in that specific form.
});

这篇关于jQuery获取所有表单元素:input,textarea和选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆