user441964
user441964

Reputation: 53

Binding same function to different elements in jquery

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>

Upvotes: 1

Views: 285

Answers (4)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

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");
});

Upvotes: 2

Bas Wildeboer
Bas Wildeboer

Reputation: 580

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");})        
    });

Upvotes: 1

Umesh Patil
Umesh Patil

Reputation: 10685

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");
    });

Upvotes: 1

paulcol.
paulcol.

Reputation: 3000

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);

Upvotes: 1

Related Questions