jrs
jrs

Reputation: 1

If else button clicked not working

I'm trying to do something when a button is clicked, sample code below.

Fiddle

$(":button").click(function() {
   if ($(this).prop("id") == "update") {
        alert("Update clicked");
    }
    else {
        alert("Add clicked");   
    }
}); 

This works in fiddle, but strangely does not work on my localhost.

I get an error (Uncaught SyntaxError: UnExpected token Illegal) at this line:

if ($(this).prop("id") == "update") {

I'm using jQuery 1.10.0.

Any idea why?

Upvotes: 0

Views: 114

Answers (3)

Sagar Pathak
Sagar Pathak

Reputation: 406

This is working for me. Please check this in your browser too.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
    <script>
    $(document).ready(function(){
        $(":button").click(function(){
           if($(this).prop("id") == "update"){
                alert("Update clicked");
            }
            else {
                alert("Add clicked");   
            }
        });
    });
    </script>
</head>
<body>
<button id="update" type="button">UPDATE</button>
<button id="add" type="button">ADD</button>
</body>
</html>

Upvotes: 5

Robin
Robin

Reputation: 471

<input type="button" id="update" data-type="update" />

in js write the following code

$(":button").click(function() {
    if ($(this).attr("data-id") == "update") {
        alert("Update clicked");
    }
    else {
        alert("Add clicked");   
    }
 }); 

Or Try these things

$(this).attr('id');
or
$(this).get(0).id;
or
$(this)[0].id;

Upvotes: 0

Weafs.py
Weafs.py

Reputation: 22992

Try using this.id:

$(":button").click(function () {
    if (this.id == "update") {
        alert("Update clicked");
    } else {
        alert("Add clicked");
    }
});

Fiddle

Upvotes: 0

Related Questions