勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

jQueryでformの各種パーツ(テキストボックス等)の操作まとめ

   2024/04/15  jQuery JavaScript

jQueryでフォームのセレクトメニューやラジオボタン等、各種パーツを操作することは多々あるもののテキストボックス及びテキストエリア以外は毎回Google検索していた。さすがに毎回検索するのは面倒臭い上に時間がかかるのでこのページにまとめておく。

 

テキストボックス <input type="text">

以下テキストボックスを設置する想定。

<input type="text" name="text_box" id="text_box" data-key="test_key">

値の取得

//valueの取得
const text_box = $('#text_box').val();
//カスタムデータ属性の取得
const key = $('#text_box').data('key');

値を削除(空にする)

$('#text_box').val('');

値を入れる

$('#text_box').val('hoge');

バリデート(空チェック)

const text_box = $('#text_box').val();
if( !text_box ){
    alert('入力されていません。');
    return false;
}

 

テキストエリア <textarea>

以下テキストエリアを設置する想定。

<textarea name="textarea" id="textarea" data-key="test_key"></textarea>

値の取得

//valueの取得
const textarea = $('#textarea').val();
//カスタムデータ属性の取得
const key = $('#textarea').data('key');

値を削除(空にする)

$('#textarea').val('');

値を入れる

//1行の場合
$('#textarea').val("hoge");
//複数行の場合は\nで改行
$('#textarea').val("hoge\nhoge");

バリデート(空チェック)

const textarea = $('#textarea').val();
if( !textarea ){
    alert('入力されていません。');
    return false;
}

 

セレクトメニュー <select>

以下セレクトメニューを設置する想定。

<select name="select" id="select">
    <option value="">選択してください。</option>
    <option value="0" data-price="100" data-key="apple">りんご</option>
    <option value="1" data-price="200" data-key="strawberry">いちご</option>
    <option value="2" data-price="300" data-key="grape">ぶどう</option>
</select>

選択した項目の値を取得

//valueの取得
const select = $('#select').val();
//カスタムデータ属性の取得
const price = $('#select option:selected').data('price');
const key = $('#select option:selected').data('key');
//カスタムデータ属性をname指定で取得
const price = $('[name=select] option:selected').data('price');
const key = $('[name=select] option:selected').data('key');

任意の項目を選択(valueで指定)

$('#select').val(1);

任意の項目を選択(n番目を指定)

//name指定
$(`[name=select]`).prop(`selectedIndex`, 2);

//id指定
$(`#select`).prop(`selectedIndex`, 3);

バリデート(未選択チェック)

const select = $('#select').val();
if( !select ){
    alert('選択されていません。');
    return false;
}

 

ラジオボタン <input type="radio">

以下ラジオボタンを設置する想定。

<label><input type="radio" name="radio" value="0" data-price="100" data-key="apple">りんご</label>
<label><input type="radio" name="radio" value="1" data-price="200" data-key="strawberry">いちご</label>
<label><input type="radio" name="radio" value="2" data-price="300" data-key="grape">ぶどう</label>

選択した項目の値を取得

//valueの取得
const radio = $('input[name="radio"]:checked').val();
//カスタムデータ属性の取得
const price = $('input[name="radio"]:checked').data('price');
const key = $('input[name="radio"]:checked').data('key');

任意の項目を選択

$('input[name="radio"]').val(['1']);

チェックを外す

$('input[name="radio"]').prop('checked', false);

バリデート(未選択チェック)

const radio = $('input[name="radio"]:checked').val();
if( !radio ){
    alert('選択されていません。');
    return false;
}

 

チェックボックス <input type="checkbox">

以下チェックボックスを設置する想定。

<label><input type="checkbox" name="checkbox[]" value="0" data-price="100" data-key="apple">りんご</label>
<label><input type="checkbox" name="checkbox[]" value="1" data-price="200" data-key="strawberry">いちご</label>
<label><input type="checkbox" name="checkbox[]" value="2" data-price="300" data-key="grape">ぶどう</label>

選択した項目の値を取得

//ループ処理
$('[name="checkbox[]"]:checked').each(function(index, element){
    //値の取得
    const checkbox = $(element).val();
    //カスタムデータ属性の取得
    const price = $(element).data('price');
    const key = $(element).data('key');
});

任意の項目を選択

//1つだけ選択する場合
$('input:checkbox[name="checkbox[]"]').val(['0']);
//複数選択する場合
$('input:checkbox[name="checkbox[]"]').val(['0', '1']);
//全て選択する場合
$('input[name="checkbox[]"]').prop('checked', true);

チェックを外す

//特定のチェックボックスのみ解除する場合
$('[name="checkbox[]"]:checked').each(function(index, element){
    //valueが1(いちご)の場合はチェックを解除
    if( $(element).val() == 1 ){
        $(this).prop('checked', false);
    }
});
//全て解除する場合
$('input[name="checkbox[]"]').prop('checked', false);

バリデート(未選択チェック)

if( !$('[name="checkbox[]"]:checked').length ){
    alert('選択されていません。');
    return false;
}

 

その他

値取得時は型に注意する

テキストボックスに数値を入力してもらい合計金額計算ボタンのようなものを押すと「入力した数値+予め設定してある手数料」の合計値を表示させる見積システムみたいなものを作る場合に注意したいのが、jQueryでvalueやカスタムデータ属性の値を取得すると文字列として判定される点。例えばテキストボックスに「1000」を入力、手数料が「500」だった場合は「1000500」が表示される。その為、以下のように型変換をする必要がある。

//テキストボックスの値を取得
const text_box = $('#text_box').val();

//手数料を設定
const commission = 500;

//テキストボックスの値を数値型に変更して計算
const total = Number(text_box) + commission;

 

所感

一通りまとめたので今後は検索しなくても大丈夫な筈。新たにフォーム&jQuery関連でわからないことが出てきたら本記事に追記していく。後はフォームとかのバリデート時にメールアドレス形式チェック等の正規表現関連も毎回Google検索しているのでその辺りもまとめておきたいところ。

 

参考サイト

https://qiita.com/zawascript/items/a25eaf7a222ac3671275

 - jQuery JavaScript

  関連記事

jQueryで要素を移動する方法のまとめ

jQueryで要素を移動する際、insertBefore / insertAft ...