▽1
●
a-kuma3 ●300ポイント ベストアンサー |
こんな感じかな。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> jQuery(function() { jQuery("input:text.x_txt").blur(function() { var txt1 = jQuery("input[name='name1']").val(); var txt2 = jQuery("input[name='name2']").val(); if (txt1 != "" && txt2 != "") { jQuery("input[name='label_other_entry']").attr("disabled", false); } else { jQuery("input[name='label_other_entry']").attr("disabled", true).attr("checked", false); } }); }); </script> <input type="text" name="name1" class="x_txt"><br> <input type="text" name="name2" class="x_txt"><br> <label><input type="checkbox" name="check01">チェック1</label><br> <label><input type="checkbox" name="check02">チェック2</label><br> <label><input type="checkbox" name="label_other_entry" disabled>チェックX</label><br>
テキストボックスには、class 属性を指定して、セレクタでクラス指定をした方が、イベントの定義がひとつにできるので、書き間違いによるミスが少なくなる。
「がんばって作ってみたモノ」は、HTML の部分が分からないけど、ふたつ間違いがあると思う。
例えば、"#name1 input:text" というセレクタは、「id="name1" という要素の子供の、<input type="text"> 」にマッチする。
例えば、こんなのにマッチする。
<div id="name1"> <input type="text"> </div>
んで、こういうのにはマッチしない。
<input id="name1" type="text">
このメソッドが判定しているのは、テキストが空ということではない。
.val() メソッドが取り出しているのは、<input type="text"> に入力されている文字列そのものなので、比較演算子で空文字 "" と比較しなくちゃいけない。
すでにチェックボックスにチェックをいれられていた時に、テキストボックスの中身がカラになった場合、チェックボックスのチェックを外した上でdisabledにする・・・・って、これはdisabledにした時点でvalueはカラになったような気がしますが・・・
「カラになる」というか、form の submit をしたときにパラメータとして送信されない。
なので、受け取る php なり cgi なりでは、パラメータが空になる、という感じ。
jQuery.noConflict(); (function($) { $(function() { $("input:text.x_txt").blur(function() { var txt1 = $("input[name='name1']").val(); var txt2 = $("input[name='name2']").val(); if (txt1 != "" && txt2 != "") { $("input[name='label_other_entry']").attr("disabled", false); } else { $("input[name='label_other_entry']").attr("disabled", true).attr("checked", false); } }); }); })(jQuery);
ちまたに出回ってる jQuery ネタは、やっぱり $ で書くのが多いので、合わせておいた方が何かと便利だよね(コードのコピペとか)、ということで。
http://api.jquery.com/jQuery.noConflict/
<!DOCTYPE HTML> <html lang="ja"> <head> <meta charset="utf-8"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> <script> $(function() { $('[name="name1"], [name="name2"]').on('load keyup', function(e) { if ($('[name="name1"]').val() === '' || $('[name="name2"]').val() === '') { $('#label_other_entry').attr('disabled', true); } else { $('#label_other_entry').removeAttr('disabled'); } }); }); </script> <style> </style> </head> <body> <input type="text" name="name1"> <input type="text" name="name2"> <input id="label_other_entry" type="checkbox" disabled> </body> </html>