Using jQuery, what is the approach to attaching a single event handler function to two buttons that have unique IDs,

Short Answer
Views 173

Answer:

To make both buttons trigger the same event when clicked, you can give them the same class and use the class selector instead of the ID selector in your jQuery code.

For example, suppose you have two buttons with IDs "button1" and "button2" that you want to trigger the same event. You can give them both the class "submit-button" like this:

<span class="pln">
</span><span class="tag">&lt;button</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"button1"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"submit-button"</span><span class="tag">&gt;</span><span class="pln">Submit</span><span class="tag">&lt;/button&gt;</span><span class="pln">
</span><span class="tag">&lt;button</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"button2"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"submit-button"</span><span class="tag">&gt;</span><span class="pln">Submit</span><span class="tag">&lt;/button&gt;</span><span class="pln">
</span>

Then you can use the class selector .submit-button in your jQuery code to bind the click event handler to both buttons:

<span class="pln">
$</span><span class="pun">(</span><span class="str">'.submit-button'</span><span class="pun">).</span><span class="pln">click</span><span class="pun">(</span><span class="kwd">function</span><span class="pun">(</span><span class="kwd">event</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// Your event handler code here</span><span class="pln">
</span><span class="pun">});</span><span class="pln">
</span>

Now when either button is clicked, the event handler function will be called.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of JavaScript, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.