-1

チェックボックスがオフでテキストボックスが空の場合、検証メッセージをポップアップする必要があります。ポップアップは表示されますが、入力されたテキストは削除され、無効のままになります。最初の文字が入力されたときに検証が消え、テキストボックスが空白でない限り再表示されないようにするにはどうすればよいですか?

<form  id="practiceForm">
    <input type="text" name="firstName" id="textbox"/>
    <input type="checkbox" name="active" id="checkbox"/>
    <input type="submit" id="submit" value="Submit"/>
</form>

<script type="text/javascript">
    $('#checkbox').attr('checked', true);

    if($('#checkbox').attr('checked')){
        $('#textbox').attr('disabled', true);
        $('#textbox').val('');
    } else {
        $('#textbox').attr('disabled', false);
    };


$('#checkbox').change(function () {
    if($('#checkbox').attr('checked')){
        $('#textbox').attr('disabled', true);
        $('#textbox').val('');
    } else {
        $('#textbox').attr('disabled', false);
    };
});

$.validator.addMethod("textValidate", function(value){
    if(!$('#checkbox').attr('checked')){
        if(!$('#textbox').val('') || !$('#textbox').val(null)){

            return true;
        };
    };  
}, "If box is not checked then there must be text"
);


$('#practiceForm').validate({
    rules: {
        //textValidate: true
        firstName:{ 
                    textValidate: true
                    }
                }
            });

</script>
4

2 に答える 2

2

メソッド内のこのロジックtextValidateは壊れています:

if(!$('#textbox').val('') || !$('#textbox').val(null)){

またはをチェックする代わりに、valueそれを として設定していました。このメソッドはすべてのキーアップ イベントで呼び出されるため、入力したとおりに入力を消去していました。''nullvalue

代わりにこれを試してください:

$.validator.addMethod("textValidate", function (value) {
    if (!$('#checkbox').attr('checked')) {
        if (!$('#textbox').val() == '' || !$('#textbox').val() == null) {
             return true;
        };
    };
}, "If box is not checked then there must be text");

実際のデモ: http://jsfiddle.net/s2AjA/

副次的な問題:

このコードのほとんどは必要ありません...

$('#checkbox').attr('checked', true);

if($('#checkbox').attr('checked')){
    $('#textbox').attr('disabled', true);
    $('#textbox').val('');
} else {
    $('#textbox').attr('disabled', false);
};

DOM 対応で一度だけ実行され、 as として設定され#checkboxているため、プロパティのように見える条件は完全に不要で不要です。checkedif/thenchecked

次のようにもっと簡単に書くことができます。また、jQuery 1.6 以降を使用する場合よりも技術的に正しいものに変更しattrました。propattr

$('#checkbox').prop('checked', true);
$('#textbox').prop('disabled', true);
$('#textbox').val('');
于 2013-02-03T01:53:03.727 に答える
0
if(!$('#textbox').val('') || !$('#textbox').val(null)){

の値#textboxを "" に設定してから null に設定し、if ステートメントが常に false を返すようにしています。

おそらく次のような意味です。

if ($('#textbox').val() != '' || $('#textbox').val() != null) {
于 2013-02-03T01:49:04.463 に答える