1

The following code won't work if i replace id with variable. I tried different combination but didn't work. I am using on form elements. Please let me know if anyone knows how to get this work. Thanks.

This works:

$('#Button1, #Button2').click(function() {
// 
});

Here is my sample code that doesn't work:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Untitled Document</title>
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>                    <script>    
    $(document).ready(function(){
   var Btn1 = $("#buy");
       var Btn2 = $("#preview");        
   $(Btn1, Btn2).click(function(){ console.log("hey");})        
});

</script>
</head>
<body>
  <form>
      <input type="button" value="Preview" id="preview" />
      <input type="button" value="Buy" id="buy" />
  </form>

</body>
</html>
1
  • 1
    Side note: you should indent your code properly if you don't want to get lost in a labyrinth of jQuery chained methods. Commented Dec 30, 2011 at 11:27

4 Answers 4

2

You can concat jQuery elements and assign click function on both.

Btn1.add(Btn2).click(function(){ 
    console.log("hey");
});

Better solution would be giving some class to buttons then assigning click on them:

$('.myButton').click(function() { 
    console.log("hey");
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can also separate the function from the event binding. This can a powerful technique for more advance uses.

var my_func = function(){ console.log("hey");}

$("#buy").click(my_func);
$("#preview").click(my_func);

Comments

1

More easy solution :)

$("input[type='button']").click(function(){
   console.log("hey");
});

Or simply give common style class to all buttons

 <input type="button" class=".buttonClass" value="Preview" id="preview" />
 <input type="button" class=".buttonClass" value="Buy" id="buy" />

below is the required javascript.

  $(".buttonClass").click(function(){
           console.log("hey");
    });

Comments

1

You are putting your jquery elements in separate variables and are using these in your function call. The comma will not act as expected in your solution. You can use the selector like this $('#buy, #preview'). Your JS code would then look like this:

    $(document).ready(function(){
       $('#buy, #preview').click(function(){ console.log("hey");})        
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.