BringQBasicBack
BringQBasicBack

Reputation: 119

Ajax function with multiple buttons for a .click event

I have a form with two buttons that have the same name and id (don't ask me why, I didn't create the form lol). I am trying to use Ajax .click function to run when the buttons are clicked. However, the function is only working with the "Approve" button and not the "Forward" button. Is there anyway to call this function from the Forward button?

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btnApprove").click(function(){
   alert("Button was clicked.");
  });
});
</script>
</head>
<body>
    <input type="submit" name="btnSubmit" id="btnApprove" value="Approve" tabindex="1102" />

    <input type="submit" name="btnSubmit" id="btnApprove" value="Forward" tabindex="1102" />
</body>
</html>

I modified the code from http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_click

Upvotes: 2

Views: 2012

Answers (3)

psoshmo
psoshmo

Reputation: 1550

add a class attribute to both buttons, putting them in the same class then you should be able to do something like

  $('.NameOfClassHere').click(function(){

or

  $('.NameOfClassHere').live('click', function () {

This will work for the click event of all buttons in that class, so saves you from using duplicate code. Also, agreed that you should not use duplicate IDs. Hopefully this helps.

Upvotes: 0

user3508122
user3508122

Reputation: 674

No two elements on a page should have the same id.

$("#btnApprove") maps the the native document.getElementById method which returns the first instance of an element of that id, so the event is only being bound to the first button

Upvotes: 0

dersvenhesse
dersvenhesse

Reputation: 6414

IDs must be unique. Even if they aren't unique, jQuery only selects the first occurence. You should change the IDs to be unique.

But anyway, you select per name instead:

$("input[name=btnSubmit]").click(function(){
    alert("Button was clicked.");
}); 

Upvotes: 2

Related Questions