あなたはこれを行うことができます:
var fields = {};
$("#theForm").find(":input").each(function() {
// The selector will match buttons; if you want to filter
// them out, check `this.tagName` and `this.type`; see
// below
fields[this.name] = $(this).val();
});
var obj = {fields: fields}; // You said you wanted an object with a `fields` property, so...
フォームには名前が繰り返されるフィールドが含まれる可能性があり、実行しようとしていることはそれをサポートしていないことに注意してください。また、HTMLフォームのフィールドの順序が重要になる場合があります。(これらは両方とも、そのように機能する理由ですserializeArray
。)
通常のHTMLの慣例では、無効なフィールドを省略します。それを行いたい場合はthis.disabled
、値を取得する前にも確認してください。
上記(2年前に書かれた)はjQuery疑似セレクターを使用していることに注意してください。私がそれを書いたことに少し驚いています。疑似セレクターのドキュメントに記載され:input
ているように、これを使用すると、jQueryはセレクターをブラウザーのネイティブquerySelectorAll
(現在ほとんどすべてのブラウザーにあります)に渡すことができません。
今日、私はおそらく次のように書くでしょう:
$("#theForm").find("input, textarea, select, button")...
...ボタンが必要な場合、またはそうでない場合
$("#theForm").find("input, textarea, select")...
...そして、フィルターで除外input[type="button"]
しinput[type="submit"]
ますeach
。例(ボタンはまったくありません):
$("#theForm").find("input, textarea, select").each(function() {
var inputType = this.tagName.toUpperCase() === "INPUT" && this.type.toUpperCase();
if (inputType !== "BUTTON" && inputType !== "SUBMIT") {
// ...include it, either it's an `input` with a different `type`
// or it's a `textarea` or a `select`...
}
});