2015-10-16 54 views
0

I know it's easy to do using < button > or < input type="submit" but how would you keep this button disabled unless both input fields are filled?禁用<a class button if input fields empty

<input id="one" type="text"> 
<input id="two" type="text"> 
<a href="#" class="button">OK</a> 

回答

1

Tie an event to both inputs, and check that both have values. Then enable the link.

$('#one, #two').blur(function() { 
    if($('#one').val() !== "" && $('#two').val() !== "") { 
     $('.button').attr('href','#'); 
    } else { 
     $('.button').removeAttr('href'); 
    } 
}); 

and change your html to:

<a class="button">OK</a> 

so that the link is disabled on page load. Here's a JSFiddle demo

+0

你釘了它!謝謝。 – VitalSigns

0

$(document).ready(function(){ 
 
     //$(".button").attr('disabled', "disabled"); 
 
     $(".button").click(function(){ 
 
      one = $("#one").val(); 
 
      two = $("#two").val(); 
 
      if(one && two){ 
 
      ///both fields filled. 
 
      return true; 
 
      } 
 
      //one or both of them is empty 
 
        
 
    
 
      return false; 
 
     }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input id="one" type="text"> 
 
<input id="two" type="text"> 
 
<a href="#" class="button">OK</a>

+0

不應該是'two = $(「two」)。val()'? –

+0

是的,編輯。抱歉。 – Omidam81

0

$(document).ready(function() { 
 

 
    $inputs = $('#one,#tow'); 
 
    $inputs.change(check); 
 
    $submit = $('#submit'); 
 

 
    function check() { 
 
    var result = 1; 
 
    for (var i = 0; i < $inputs.length; i++) { 
 
     if (!$inputs[i].value) { 
 
     result = 0; 
 
     break; 
 
     } 
 
    } 
 
    if (result) { 
 
     $submit.removeAttr('disabled'); 
 
    } else { 
 
     $submit.attr('disabled', 'disabled'); 
 
    } 
 
    } 
 

 
    check(); 
 
});

建議使用角形式

0

這是我的實現,如果面臨這種情況。 首先,我在頁面加載使用此樣式添加禁用類到錨標記:

.disabled { 
    color : gray // gray out button color 
    cursor : default; // make cursor to arrow 
    // you can do whatever styling you want 
    // even disabled behaviour 
} 

我們一起添加使用的文件準備jQuery的那些類keyup事件,像這樣:

$(function() { 

    // add disabled class onto button class(anchor tag) 
    $(".button").addClass('disabled'); 

    // register keyup handler on one and two element 
    $("#one, #two").keyup(function() { 

     var one = $("#one").val(), 
      two = $("#two").val(); 
     // checking if both not empty, then remove class disabled 
     if (one && two) $(".button").removeClass('disabled'); 
     // if not then add back disabled class 
     else $(".button").addClass('disabled'); 

    }); 

    // when we pressing those button 
    $('.button').click(function (e) { 
    // we check if those button has disabled class yet 
    // just return false 
    if ($(this).hasClass('disabled')) return false; 
    }); 
}); 

DEMO