2015-06-21 107 views
1

Hy那裏,我有一個表格4 <input type='text'>和一個禁用<button>觀察DOM元素的變化

這些<input type='text>中的2個是隻讀的,並且在另一個正在給定由keyup()事件觸發的值時將自動填充。

我的問題是,當兩個「禁用」<input type='text'>已被給定值時,如何刪除<button>的「禁用」屬性?我必須在哪裏舉辦活動?

這裏是我的代碼:

<input type="text" class="firstbox" name='firstbox' required> 
<input type="text" class='automaticfilling' readonly="readonly" 
placeholder='will be filled as input.firstbox is being typed'> 

<input type="text" class="secondbox" name='secondbox' required> 
<input type="text" class='automaticfillingtwo' readonly="readonly" 
placeholder='will be filled as input.secondbox is being typed'> 

<button type='button' value='click me' disabled='disabled'> 

jQuery代碼:

$(function(){ 

$('input.firstbox').keyup(function(){ 
var value = $(this).val(); 
$('input.automaticfilling').val(value); 
}); 

$('input.secondbox').keyup(function(){ 
var value = $(this).val(); 
$('input.automaticfillingtwo').val(value); 
}); 

//In what element should I put an trigger for enabling button 
//after those two readonly textboxes has been filled? 

}); 
+0

你要觀察的隱框更改事件,當它被觸發檢查這兩個盒子都充滿,如果是的話,從移除已停用的屬性您按鈕,否則添加它。要做到這一點,你可以使用attr()或prop() –

回答

1

你會需要你以後其值設置爲檢查readonlyinput元素的狀態。如果它們都有值,則可以從button中刪除disabled屬性。試試這個:

$(function(){ 
    var $auto1 = $('input.automaticfilling'), 
     $auto2 = $('input.automaticfillingtwo'); 

    $('input.firstbox').keyup(function(){ 
     $auto1.val($(this).val()); 
     checkAutoValues(); 
    }); 

    $('input.secondbox').keyup(function(){ 
     $auto2.val($(this).val()); 
     checkAutoValues(); 
    }); 

    function checkAutoValues() { 
     $('button').prop('disabled', !($auto1.val() && $auto2.val())); 
    } 
}); 

Example fiddle

注意,當兩個框有值的按鈕將被啓用,禁用當其中任意一個沒有價值。

另請注意,通過使用DOM遍歷來查找所需的元素,您可以使JS代碼完全不知道您使用的DOM數量爲autofilling。試試這個:

<div class="auto-container"> 
    <input type="text" class="firstbox" name='firstbox' required /> 
    <input type="text" class='automaticfilling' readonly="readonly" placeholder='will be filled as input.firstbox is being typed' /> 
</div> 

<div class="auto-container"> 
    <input type="text" class="firstbox" name='firstbox' required /> 
    <input type="text" class='automaticfilling' readonly="readonly" placeholder='will be filled as input.firstbox is being typed' /> 
</div> 

<button type='button' value='click me' disabled='disabled'>Click me</button> 
$('input.firstbox').keyup(function() { 
    $(this).closest('.auto-container').find('.automaticfilling').val($(this).val()); 

    var buttonEnabled = true; 
    $('.automaticfilling').each(function() { 
     if (!$(this).val()) { 
      buttonEnabled = false; 
      return; 
     } 
    }); 
    $('button').prop('disabled', !buttonEnabled); 
}); 

Example fiddle