saltandwater
saltandwater

Reputation: 841

unable to access click event of a button in javascript

I want to access the click event of an element on my HTML page.

So, in chrome, I right-clicked the element -> selected Inspect element and got the following

<button type="submit" class="btn btn-primary" id="ben-count-submit">Update</button>

I then went to a js page and wrote the following

$("#ben-count-submit").click(function () {      
        console.log("clicked on the update button");
    });

However, when I click on the button, I don't see any console log. It just takes me back to the home page of the web site and shows the url as the start page of the site appended with a '?' at the end as follows

http://localhost/myproject/start/?

How do I access the click event of this button? Where am I going wrong?

Upvotes: 1

Views: 822

Answers (1)

renakre
renakre

Reputation: 8291

Since your button is submit type, the button causes page refresh, you need to use preventDefault().

$("#ben-count-submit").click(function (event) {      
      event.preventDefault();
});

Upvotes: 1

Related Questions