2016-03-17 14 views
-1

我有一個條件,如果兩個字段不是空的,它將顯示按鈕。我的問題是如何執行該事件,因爲它只能工作或加載網站時。我JS如果兩個或多個輸入字段不爲空,則觸發一個事件

$(document).ready(function() { 
    if ($('#email').is(':empty') && $('#username').is(':empty')){ 
    $('#login').hide(); 
    } 
    else { 
    $('#login').show(); 
    } 
}); 
嘗試使用KEYUP

HTML

<input type="text" id="username" required="true"> 
<input type="email" id="email" required="true" > 
<button type="submit" id="login"> 
Sign Up 
</button> 

https://jsfiddle.net/w0pohLeb/1/

+0

https://developer.mozilla.org/en-US/ docs/Web/Events/change –

回答

3

您可以使用input事件。

// Bind `input` event on both the inputs 
$('#email, #username').on('input', function() { 
    // toggle: If argument passed is 
    //   true: show 
    //   false: hide 
    $('#login').toggle($('#email').val() && $('#username').val()); 
}).trigger('input'); // Trigger event to call on page load 
2

不能使用.is(':empty')檢查值的空虛,它只是檢查是否標籤爲空且不包含任何兒童。相反,你需要使用:

$(input).val().trim().length === 0 

所以,你的代碼就變成了:

if ($('#email').val().trim().length === 0 && $('#username').val().trim().length === 0) { 

而且還需要將此附加到一個更好的活動,比方說,在輸入的keyup

最終代碼

$(document).ready(function() { 
    if ($('#email').val().trim().length === 0 || $('#username').val().trim().length === 0) { 
    $('#login').hide(); 
    } 
    else { 
    $('#login').show(); 
    } 
    $("#email, #username").keyup(function() { 
    if ($('#email').val().trim().length === 0 && $('#username').val().trim().length === 0) { 
     $('#login').hide(); 
    } 
    else { 
     $('#login').show(); 
    } 
    }); 
}); 
+0

它確實有效,但即使只有一個字段被填滿,按鈕也會顯示 – JeVic

+0

@JeVic沒辦法,代碼不允許它。檢查? –

+0

我只是做了https://jsfiddle.net/w0pohLeb/3/ – JeVic

-1

試試這個,希望這有助於.. :)

$(document).ready(function() { 
 

 
    $('body').on('change', 'input', validate); 
 
    validate(); 
 

 
    function validate() { 
 
    var inputLength = 0; 
 
    $('input').each(function() { 
 
     if ($(this).attr('type') == 'text' || $(this).attr('type') == 'email' || $(this).attr('type') == 'password') { 
 

 
     $(this).val() == '' ? inputLength-- : inputLength++; 
 
     } 
 

 
    }); 
 
    inputLength >= 2 ? notEmpty() : isEmpty(); 
 

 
    }; 
 

 
    function notEmpty() { 
 

 
    $('#login').show(); 
 

 
    } 
 

 
    function isEmpty() { 
 

 
    $('#login').hide(); 
 

 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="text" id="username" required="true"> 
 
<input type="email" id="email" required="true"> 
 
<button type="submit" id="login"> 
 
    Sign Up 
 
</button>

撥弄鏈接https://jsfiddle.net/j6y2d1ur/1/

相關問題