文書の過去の版を表示しています。
コピペして test.html などの htmlファイルとして保存すれば、そのまま動作確認が行なえます。
<html> <meta> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </meta> <body> <input type="text" name="hoge" value="" id="input-01" class="form-hoge"> <button type="button" class="form-change">change</button> <button type="button" class="form-clear">clear</button> <script> $(function() { $('.form-hoge').on('change', function(){ // id で value を取得 let hoge_id = $('#input-01').val(); console.log(hoge_id); // class で value を取得 let hoge_class = $('.form-hoge').val(); console.log(hoge_class); // name で value を取得 let hoge_name = $('input[name=hoge]').val(); console.log(hoge_name); }); $('.form-change').on('click', function(){ // value の変更 $('.form-hoge').val('abc'); }); $('.form-clear').on('click', function(){ // value を空にする $('.form-hoge').val(''); }); }); </script> </body> </html>
<html> <meta> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </meta> <body> 性別 <label><input type="radio" name="figure" value="male" id="form-figure-male" class="form-figure">男性</label> <label><input type="radio" name="figure" value="female" id="form-figure-female" class="form-figure">女性</label> <button type="button" class="form-change-male">change male</button> <button type="button" class="form-change-female">change female</button> <button type="button" class="form-clear-1">clear 1</button> <button type="button" class="form-clear-2">clear 2</button> <script> $(function() { $('.form-figure').on('change', function(){ // class でチェック状態(checked)を取得 let figure_class = $('.form-figure:checked').val(); console.log(figure_class); // name でチェック状態(checked)を取得 let figure_name = $('input[name=figure]:checked').val(); console.log(figure_name); }); $('.form-change-male').on('click', function(){ // チェック状態(checked)を val で変更 $('input[name=figure]').val(['male']); }); $('.form-change-female').on('click', function(){ // チェック状態(checked)を prop で変更 $('#form-figure-female').prop('checked', true); }); $('.form-clear-1').on('click', function(){ // チェック状態(checked)を val で解除 $('input[name=figure]').val(['']); }); $('.form-clear-2').on('click', function(){ // チェック状態(checked)を prop で解除 $('.form-figure').prop('checked', false); }); }); </script> </body> </html>
コメント