LoginSignup
179
176

More than 5 years have passed since last update.

コピペで使えるフォーム値取得jQuery

Last updated at Posted at 2013-07-31

(2014-07-07 追記)

フォーム値取得&設定するjQueryプラグイン作ったので、良ければそちらも。

(追記おわり)

共通: 要素検索

name属性で検索するのが手っ取り早くて良いと思います。

<form id="my-form">
  <input type="text" name="my-text" value="This is text." />
</form>
var $input = $('#my-form [name=my-text]');

テキスト

<form id="my-form">
  <input type="text" name="my-text" value="This is text." />
</form>
var val = $('#my-form [name=my-text]').val();
console.log(val);  // => "This is text."

数字のときはval=Number(val)||0;とかしてください。

ラジオボタン

<form id="my-form">
  <input type="radio" name="my-radio" value="A" />
  <input type="radio" name="my-radio" value="B" checked />
  <input type="radio" name="my-radio" value="C" />
</form>
var val = $('#my-form [name=my-radio]:checked').val();
console.log(val);  // => "B"

チェックボックス

<form id="my-form">
  <input type="checkbox" name="my-checkbox" value="A" />
  <input type="checkbox" name="my-checkbox" value="B" checked />
  <input type="checkbox" name="my-checkbox" value="C" checked />
</form>
var $checked = $('#my-form [name=my-checkbox]:checked');
var valList = $checked.map(function(index, el) { return $(this).val(); });
console.log(valList);  // => ["B", "C"]

セレクトボックス(単数)

<form id="my-form">
  <select name="my-select">
    <option value="A">This is A</option>
    <option value="B" selected>This is B</option>
    <option value="C">This is C</option>
  </select>
</form>
var val = $('#my-form [name=my-select]').val();
console.log(val);  // => "B"

// おまけ: 値ではなくラベル文字列が欲しいとき
var text = $('#my-form [name=my-select] option:selected').text();
console.log(text);  // => "This is B"

セレクトボックス(複数)

<form id="my-form">
  <select name="my-multi-select" size="3" multiple>
    <option value="A">This is A</option>
    <option value="B" selected>This is B</option>
    <option value="C" selected>This is C</option>
  </select>
</form>
var val = $('#my-form [name=my-multi-select]').val();
console.log(val);  // => ["B", "C"]

元ネタ

というか、そのまんま。自分のブログから転載。

179
176
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
179
176