jQuery - Combing If / Else + .Click()和.prop(' disabled',true);

时间:2017-02-24 23:34:39

标签: javascript jquery

当我在StackOverFlow上搜索并找到一种方法来禁用按钮点击IF没有信息输入到表单中时,会对此有所帮助吗(使用$ .trim(.....)代码如下!耶! 问题是 - 一旦我加入,其余的代码在" else"部分不起作用。为什么要抓我的头?!!

如果我注释掉此部分以禁用点击,则用户可以点击该按钮,无论是否输入任何信息(但其余代码都可正常工作) -

if ($.trim($('.inputs').val()).length == 0){
$('.inputs').prop('disabled', true);
} else { ....... } 

我的HTML -

<div class="entry"> 
<h2>Enter the Contest:</h2>
<form>
<p class="inputs"><label>Name : </label><input type="text"   placeholder=" required" id="name-input" required></p>
<p class="inputs"><label>Hole #: </label><input type="number" placeholder=" required" id="hole-input" required></p> 
<p class="inputs"><label>Par #: </label><input type="number" placeholder=" required" id="par-input" required></p>
<p class="inputs"><label>Strokes #: </label><input type="number" placeholder=" required" id="strokes-input" required></p>   
<button id="submit" class="btn1">Submit</button>    
</form>
</div>  

我的jQuery -

$(document).ready(function(){
$(".btn1").click(function(){

if ($.trim($('.inputs').val()).length == 0){
$('.inputs').prop('disabled', true); 
} else { 
$(".entry h2").replaceWith("<h2>Submitted!</h2>");
$("form").hide().replaceWith("<p>" + golfScore() + "! <br>Thank you for entering the contest and good luck!</p>");
$(".entry p").addClass("inputs message");
$(".entry").append("<button>Replay?</button>");
$(".entry button").addClass("btn2");
$(".btn2").on('click', refreshPage); 
} // closes else
});     
}); // closes Doc Ready

1 个答案:

答案 0 :(得分:0)

试试这个 - 例如:

 $("input").on("change keyup",function(){
 //remove the disabled then do the rest -- 

    $('.btn1').removeAttr('disabled'); 
    // start checking if the input boxes have values

     if ($.trim($('#name-input').val()).length == 0){
     // you can also set focus to the field that is empty
            $('.btn1').prop('disabled', true); 
            return false;

     }if ($.trim($('#hole-input').val()).length == 0){

            $('.btn1').prop('disabled', true); 
            return false;

     }if ($.trim($('#par-input').val()).length == 0){

            $('.btn1').prop('disabled', true); 
            return false;

     }if ($.trim($('#strokes-input').val()).length == 0){

            $('.btn1').prop('disabled', true); 
            return false;

     } else { 
     // if all has been passed should execute code
        $(".entry h2").replaceWith("<h2>Submitted!</h2>");

        $("form").hide().replaceWith("<p>" + golfScore() + "! <br>Thank you for entering the contest and good luck!</p>");

        $(".entry p").addClass("inputs message");

        $(".entry").append("<button>Replay?</button>");

        $(".entry button").addClass("btn2");

        $(".btn2").on('click', refreshPage);

    } // closes else
    });