Eric.18
Eric.18

Reputation: 473

Disable button based on attribute in javascript

I have a form which processes data and puts it in to a csv. A user can add multiple rows to the form to add a new item. To make this a unique item the id is incremented by 1 (ex. item[0] goes to item1)

The form works great but I am trying to add a delete / remove button. It works except I don't want it to remove the very last item.

Below is the code I am using. I am having trouble as this if statement breaks the add crew button.

    $('#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 you comment out the if statement, and run the jsfiddle all the buttons work but you are able to delete the last form area.

jsfiddle

Upvotes: 0

Views: 90

Answers (3)

DWX
DWX

Reputation: 2340

Try this:-

Replace

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

with

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

Upvotes: 0

meatFeed
meatFeed

Reputation: 124

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

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

Upvotes: 0

epascarello
epascarello

Reputation: 207501

In the console it says:

Uncaught SyntaxError: Unexpected identifier

Looking at where the error is you can see the attribute method is not properly closed.

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

It should be

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

Upvotes: 5

Related Questions