問題 × 解決策

フォームのラジオボタンの選択によって入力項目を変える方法

問題

フォームのラジオボタンの選択によって入力項目を変えるには?

解決策

「$('ラジオボタンのセレクタ').change( function() { ... })」でラジオボタンが選択された時(値が変更された時)に処理を行う。

 

ラジオボタンが選択された時に処理を行う。

フォームのラジオボタンの選択によって入力項目を変える方法をご紹介します。

DEMOはこちら

 

フォームの作成

まず、フォームの作成を行います。

HTML

<form action="" method="post" class="radiochange">
<p class="ta_center"><select name="selectitem">
<option value="user01">個人の方</option>
<option value="user02">法人の方</option>
</select></p>
<table class="type02 sp-block td-tal usergroup user01">
<tbody>
<tr>
<th scope="row"><label for="ind_name">名前</label></th>
<td><input type="text" id="ind_name" class="ind_name input-text" name="ind_name" size="60"></td>
</tr>
<tr>
<th scope="row"><label for="ind_kana">ふりがな</label></th>
<td><input type="text" id="ind_kana" class="ind_kana input-text" name="ind_kana" size="60"></td>
</tr>
<tr>
<th scope="row"><label for="ind_place">住所</label></th>
<td><input type="text" id="ind_place" class="ind_place input-text" name="ind_place" size="60"></td>
</tr>
</tbody>
</table>
<table class="type02 sp-block td-tal usergroup user02">
<tbody>
<tr>
<th scope="row"><label for="cor_name">会社名</label></th>
<td><input type="text" id="cor_name" class="ind_name input-text" name="cor_name" size="60"></td>
</tr>
<tr>
<th scope="row"><label for="ind_kana">ふりがな</label></th>
<td><input type="text" id="ind_kana" class="ind_kana input-text" name="ind_kana" size="60"></td>
</tr>
<tr>
<th scope="row"><label for="cor_place">住所</label></th>
<td><input type="text" id="cor_place" class="cor_place input-text" name="cor_place" size="60"></td>
</tr>
</tbody>
</table>
</form>

フォームのラジオボタンの選択によって入力項目を切り替える記述例

フォームのラジオボタンの選択によって入力項目を切り替える記述例は以下となります。

$('table.user01').fadeIn(0);
$('table.user01 input').prop("disabled", false);
$('table.user02').fadeOut(0);
$('table.user02 input').prop("disabled", true);
$('form input.usertype').change( function() {
	if( $('form input.usertype[value="user01"]').prop('checked') ){
		$('table.user02 input').prop("disabled", true);
		$('table.user02').fadeOut(500,function(){
			$('table.user01').fadeIn(500);
			$('table.user01 input').prop("disabled", false);
		});
	}
	if( $('form input.usertype[value="user02"]').prop('checked') ){
		$('table.user01 input').prop("disabled", true);
		$('table.user01').fadeOut(500,function(){
			$('table.user02').fadeIn(500);
			$('table.user02 input').prop("disabled", false);
		});
	}
});

ポイント!

  • $(‘ラジオボタンのセレクタ’).change( function() { … })」でラジオボタンが選択された時(値が変更された時)に処理を行います。
  • if( $(‘ラジオボタンのセレクタ[value=”特定のラジオボタンのvalue属性の値”]’).prop(‘checked’) )」で、特定のラジオボタンが選択されていた場合の処理を行います。

コメント

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

2 × one =

「問題 × 解決策」
月別アーカイブ一覧

「問題 × 解決策」
月別アーカイブ一覧