[jQuery] フォームの値とテキストを取得する方法

jQueryを使ってフォームの値やラベルの値を取得する方法です。
インプットボックスの値を取得
1 2 3 |
<h2>インプットボタン</h2> <input type="text" id="seasonA" value="春"> <input type="button" value="選択" onClick="SeasonSampleA();"> |
1 2 3 4 5 6 |
<script type="text/javascript"> function SeasonSampleA() { var season = $('#seasonA').val(); console.log(season); } </script> |
seasonSampleA()という関数を作成します。 idがseasonAのインプットボックスの値は $(‘#seasonA’).val(); で取得できます。ボタンのonClickに関数seasonSampleA()を設定します。
↓プログラム実行結果
テキストボックスに入力された文字がコンソールに出力されました。
ラジオボタンの値・ラベル値を取得
1 2 3 4 5 6 7 8 |
<h2>ラジオボタン</h2> <label><input type="radio" name="seasonB" value="0" checked>春</label> <label><input type="radio" name="seasonB" value="1">夏</label> <label><input type="radio" name="seasonB" value="2">秋</label> <label><input type="radio" name="seasonB" value="3">冬</label><br> <input type="button" value="選択(Value表示)" onClick="SeasonSampleB1();"> <input type="button" value="選択(テキスト表示)" onClick="SeasonSampleB2();"> |
1 2 3 4 5 6 7 8 9 10 11 |
<script type="text/javascript"> function SeasonSampleB1() { var season = $('[name=seasonB]:checked').val(); console.log(season); } function SeasonSampleB2() { var season = $('[name=seasonB]:checked').parent('label').text(); console.log(season); } </script> |
↓プログラム実行結果 選択(Value表示)を押した時
春のvalue値は0なので0と表示されます。
↓プログラム実行結果 選択(テキスト表示)を押した時
テキストがそのまま表示されます。
チェックボックスの値・ラベル値を取得
1 2 3 4 5 6 7 |
<h2>チェックボックス</h2> <label><input type="checkbox" class="seasonC" value="0" >春</label> <label><input type="checkbox" class="seasonC" value="1">夏</label> <label><input type="checkbox" class="seasonC" value="2">秋</label> <label><input type="checkbox" class="seasonC" value="3">冬</label><br> <input type="button" value="選択(Value表示)" onClick="SeasonSampleC1();"> <input type="button" value="選択(テキスト表示)" onClick="SeasonSampleC2();"> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script type="text/javascript"> function SeasonSampleC1() { var season = $('.seasonC:checked').map(function () { return $(this).val(); }).get(); console.log(season); } function SeasonSampleC2() { var season = $('.seasonC:checked').map(function () { return $(this).parent('label').text(); }).get(); console.log(season); } </script> |
↓プログラム実行結果 選択(Value表示)を押した時
チェックされている項目のValue値が配列で表示されます。
↓プログラム実行結果 選択(テキスト表示)を押した時
チェックボックスのラベルの文字が配列で表示されます。関連記事
- [jQuery] 子ウィンドウのチェックボックスの値を親ウィンドウに渡す方法
- [Vue.js] フォーム入力バインディング一覧
- [CakePHP] Formヘルパーのinputでdivやlabelをカスタマイズする方法
- [JavaScript] onClick()を使ってフォームのボタンが押されたときの処理を作る
- [JavaScript] 現在のURLやパラメタを取得する方法(Location)