LoginSignup
4
2

More than 5 years have passed since last update.

jqueryで任意のnameを振ってあるinputに配列を使ってアクセスする方法

Last updated at Posted at 2016-06-20

nameがバラバラ、でも配列にまとめてからアクセスしたいの。。。

 そんな状況にはならないのが一番かもしれませんが、そうもいかないのがシャバというもの。というわけで、下記のようなHTMLがあるとします。

sampleForm.html
<form>
    <input type="text" size="3" name="old" value="32">
    <input type="text" size="10" name="familyName" value="rotelstift">
    <input type="text" size="10" name="favorite" value="oyako_don">
</form>

 このinputを配列にまとめたいけど、nameがバラバラだから配列にできないかなぁ。。。

そうだわ、serializeArray()さんに甘えてみましょう!

 serializeArray()を使うと、formの要素を.nameと.valueにアクセスできるハッシュの配列にして返してくれます。

sample.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
	   <title>Sample</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script>
      window.onload = function () {

        // ここで$("input")に当てはまるinputを配列にする
        var inputAry = $("input").serializeArray();

        for(i = 0; i < inputAry.length; i++){
          // $("[name=" + inputAry[i].name + "]")でアクセスできるようになる
          $("div#hoge").append($("[name=" + inputAry[i].name +"]").val() + "<br />");
        }

      };
    </script>
  </head>
  <body>
    <form>
      <input type="text" size="3" name="old" value="32">
      <input type="text" size="10" name="familyName" value="rotelstift">
      <input type="text" size="10" name="favorite" value="oyako_don">
    </form>
    <div id="hoge"></div>
  </body>
</html>

 これでいろんなnameのinputに楽々アクセス!

【追記】これって直接inputオブジェクト取れないの?

 結論から言うと、取れません。この場合返ってくるのは.nameと.valueでしかアクセスできないハッシュの配列です。この機能は、単純にそれだけ取れれば用が足りる場合を想定しているっぽい。
 でもそれだけじゃ用が足らないよ、という場合に、$("[name=" + inputAry[i].name + "]")という力技でinputオブジェクトを取り直しましょう、というお話です。

4
2
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
4
2