观察DOM元素的变化

时间:2015-06-21 08:58:02

标签: jquery html css jquery-ui

在那里,我有一张包含4 <input type='text'>和禁用<button>的表单。

其中2个<input type='text>是只读的,当另一个被keyup()事件触发时,将自动填充#{1}}。

我的问题是,我如何删除<button>的&#34;禁用的属性&#34;当那两个&#34;禁用&#34; <input type='text'>已被赋予价值?我在哪里举办活动?

这是我的代码:

<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?

});

1 个答案:

答案 0 :(得分:1)

设置值后,您需要检查readonly input元素的状态。如果它们都有值,则可以从disabled中删除button属性。试试这个:

$(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代码与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

相关问题