基于javascript中的属性禁用按钮

Disable button based on attribute in javascript

本文关键字:按钮 属性 javascript 基于      更新时间:2023-09-26

我有一个处理数据并将其放入csv的表单。用户可以向表单中添加多行以添加新项目。为了使其成为唯一项目,id增加1(例如,项目[0]转到项目1(

表单运行良好,但我正在尝试添加一个删除/删除按钮。它有效,只是我不希望它删除最后一项。

下面是我正在使用的代码。如果语句破坏了"添加船员"按钮,我会遇到麻烦。

    $('#btnDelelte').click(function () {
        //remove the last form item
        $('.questions:last-child').remove();
        // if only element that remains as ID == 0, disable the "remove" button
        if ($('.questions:last-child').attr('id' == 0) 
            $('#btnDelelte').attr('disabled', 'disabled');
    });

如果您注释掉If语句,并运行jsfiddle,所有按钮都可以工作,但您可以删除最后一个表单区域。

jsfiddle

控制台中显示:

未捕获的SyntaxError:意外的标识符

查看错误所在的位置,可以看到属性方法没有正确关闭。

if ($('.questions:last-child').attr('id' == 0)  

应该是

if ($('.questions:last-child').attr('id') == 0) 
                                        ^
 $('#btnDelelte').click(function () {           
       if($('.questions').length > 1){
           $('.questions:last-child').remove();
       }               
       });

Fiddle:http://jsfiddle.net/V2TAt/4/

试试这个:-

更换

if ($('.questions:last-child').attr('id' == 0) 
            $('#btnDelelte').attr('disabled', 'disabled');

带有

if ($('.questions:last-child select').attr('id') == "town[0]")
           $('#btnDelelte').attr('disabled', 'disabled');