单击按钮时禁用特定表单域

时间:2015-12-16 21:20:30

标签: javascript php jquery html

我已禁用按钮点击的特定字段,例如,我的页面中有两个表单,如下所示

< form method='post' action='' class='myform'>
<input type='text' name='name_0'>
<input type='email' name='email_0'>
<input  class='btn' type='submit'>
</form>

< form method='post' action='' class='myform'>
<input type='text' name='name_1'>
<input type='email' name='email_1'>
<input  class='btn' type='submit'>
</form>

使用jquery我可以禁用所有这样的字段

$(document).ready(function(){                            
    $('.btn').click(function(){
        $("input").prop('disabled', true);
    });
});

但是当我第一次提交按钮时,我不知道如何定位特定字段,如name_0,email_0,请帮我解决这个问题

2 个答案:

答案 0 :(得分:6)

要禁用它们,您可以使用属性选择器:

$("input[name='name_0']").prop('disabled', true);

jQuery Attribute Selectors

如果您有多个项目,可以将它们组合在一起:

$("input[name='name_0'],input[name='email_0']").prop('disabled', true);

更大的问题是,您通过单击某个类来确定表单。为了缩小范围,你可以做一些DOM遍历:

$(document).on('click', '.btn', function(event) {
    // which form? this one!
    var currentForm = $(this).closest('form');
    // disable all inputs for this form
    currentForm.find('input').prop('disabled', true);
});

现在我不必知道要禁用哪些输入(如果我想禁用所有输入)。我只需要在我的按钮形式中找到输入。

答案 1 :(得分:3)

你应该阅读selectors

$("input[name=name_0]").prop('disabled', true);

或jquery解决方案,您可以使用.closest()和.find()

来定位它
$(document).ready(function(){                            
    $('.btn').click(function(e){
        e.preventDefault();
        $(this).closest('form').find("input[type=text]").prop('disabled', true);
        $(this).closest('form').find("input[type=email]").prop('disabled', true);
    });
});

提交表单并禁用所有输入,并专注于下一个表单上的下一个第一个输入

$(document).ready(function(){                            
    $('.myform').on('submit',function(e){
        e.preventDefault();
        $(this).closest('form').find("input").prop('disabled', true);
        $(this).next('form').find('input:first').focus();
    });

});

Working Demo

相关问题