Alan
Alan

Reputation: 1287

jQuery Button click not firing issue

I am trying to implement a previous button on a test app. I cant get button id="prev" to fire. I am keeping it simple like this:

//Begin Previous Button Click Function
  //
  $("#btn2").click(function() {
      alert("i'm in previous button click");
  });
  // End of Previous Click Function

Here is the jsfiddle I get nothing in the console and setting a break point in function does not get called when stepping thru program. I checked the DOM to make sure btn2 was there and it is. Any suggestion appreciated.

Upvotes: 0

Views: 54

Answers (3)

Ravenous
Ravenous

Reputation: 194

The element doesn't exist when the document is ready, because you inserted it after to the DOM.

Try with this instance:

$(document).on("DOMNodeInserted", function() {
    // Call your prev button function or insert the code here
});

Upvotes: 0

Matthew Lymer
Matthew Lymer

Reputation: 977

Your question doesn't seem to make sense - if you want the item with id="prev" to fire, then your selector should be;

$("#prev")

not

$("#btn2")

Upvotes: 0

Satpal
Satpal

Reputation: 133403

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

As you are creating elements dynamically. You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).

General Syntax

$(staticParentElement).on('event','selector',callback_function)

Example

$('#div2').on('click', '#prev', function(){ 
     //Your code
});

Upvotes: 1

Related Questions