Ekene
Ekene

Reputation: 51

How To Call A Javascript Function From Inside Jquery When An ID is Clicked

Let's say I have a javascript function called capturedata(); I need to call this function when this button is clicked

<button id='yes'></button> 

For some reasons, I do not want to use any event handler on the html like onclick='capturedata()' Now I have use Jquery this way

$(document).ready(function(){
  $("#yes").click();
  capturedata();
});

But this is not working. I need a better way to handle this, and I do not want to use any event handler like onclick on the html. I want the action to happen automatically once the button is clicked.

Upvotes: 0

Views: 1744

Answers (3)

аlex
аlex

Reputation: 5698

$(document).ready(function(){
  $("#yes").click(function(){
    capturedata();
    // some code
  });
});

Upvotes: 1

phuzi
phuzi

Reputation: 13060

Almost but not quite, you'll need to register capturedata as the callback for the click event.

$(document).ready(function(){
    $("#yes").click(capturedata);
});

Upvotes: 2

Francis Leigh
Francis Leigh

Reputation: 1960

Your click method requires a callback function as its first argument

e.g .click(() => {})

see DOCS

Note how calling .click() will invoke a click event and not listen for one.

Suggestion : use addEventListener('click', {yourCallback}) see DOCS

Upvotes: 1

Related Questions