Antony West
Antony West

Reputation: 1497

Make button trigger function in jquery

I have the following jQuery code :

$("#btnReset").click(function () {
    ColReorder.fnReset(oTable);
    return false;
});

And the HTML as follows :

<div style="padding: 5px 5px 1px 0px; float: right" id="globalbutton-row" class="ex">
    <button class="button" type="button" id="btnReset"><%=rb.getString("button.reset")%></button>
    <button class="button" type="button" id="btnDeveloperSampleMenu" onclick="javascript:CallDeveloperSampleMenu()"><%=rb.getString("button.devsamplemenu")%></button>
</div>

I want the button 'Reset' to launch the function ColReOrder.fnReset but for some reason this does not work.

Upvotes: 0

Views: 234

Answers (3)

D.A
D.A

Reputation: 2601

You have to be careful to not reference anything in the DOM that isn't loaded yet. If the <button> is not loaded into the DOM before your code is fired, nothing will happen. You can fix this by running your code when everything is loaded:

$(document).ready(function() {
  $("#btnReset").click( function () {
    ColReorder.fnReset( oTable );
    return false;
  } );
});

Also if the <button> is added via AJAX or some other way, you will have the same problem. You can fix this by using the on() method:

$(document).ready(function() {
  $(document).on('click',"#btnReset", function(event) {
    ColReorder.fnReset( oTable );
    return false;
  } );
});

Upvotes: 2

dualed
dualed

Reputation: 10502

You have to execute your code after the document was loaded.

$(function() {
  $("#btnReset").click( function () {
    ColReorder.fnReset( oTable );
    return false;
  });
});

Upvotes: 0

bluetoft
bluetoft

Reputation: 5443

try using event delegation. Chances are the element hasn't loaded into the dom when your javascript is getting executed. attaching the click event to the document will make the code work by listening to click and then searching for your selector at the time of the click.

$(document).on('click','#btnReset',function () {
  ColReorder.fnReset( oTable );
  return false;
  } );

Upvotes: 1

Related Questions