One function for multiple buttons with different ID

I have

$('#BtOpenFile').click(function () { SetTimeextendBtn(); });

      

But there are several buttons with different IDs for example #BtAquire, #BtDelete, ...

, and I want to use SetTimeextendBtn()

for all my buttons. I don't want to repeat this function.

How can we do this?

+3


source to share


4 answers


You can add multiple IDs to the selector using comma

$('#BtOpenFile, #BtAquire').click(function () { SetTimeextendBtn(this); });

      

Pass the current object to SetTimeextendBtn (this);

function SetTimeextendBtn(source)
{
    alert(source.id);
}

      

Another approach should be considered, using the same class to which you want to bind the click handler. Suppose you have a button with a generic class .btn



 $('.btn').click(function () { SetTimeextendBtn(this); });

      

Note: if your click handler just calls a function and passes the current object, you can directly pass the function to click:

$('.btn').click(SetTimeextendBtn);

      

You can access source (object) button in SetTimeextendBtn

using this

for DOM object and $(this)

jQuery object for button click.

+6


source


Use the class.

Also, if nothing happens in the anonymous function, cancel it and attach another function directly

$('.BtActions').on("click",SetTimeextendBtn);



If you need to know what was clicked, you can access the button directly in the function:

function SetTimeextendBtn() {
  var id = this.id; // or $(this).prop("id");
}

      

+6


source


You can use Attribute Starts With Selector [name ^ = "value"] , this will select all elements that have id starting with . But it's better to use a common name for all these buttons. Bt

class

$('[id^=Bt]').click(function() {
  SetTimeextendBtn(this);
});

function SetTimeextendBtn(ele) {
  alert(ele.id);
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="Bt1">a</button>
<button id="Bt2">b</button>
<button id="Bt3">c</button>
<button id="Bt4">d</button>
<button id="Bt5">e</button>
      

Run codeHide result


+2


source


You can use multiple selectors :

$('#BtOpenFile, #BtAquire, #BtDelete').click(function () {
    SetTimeextendBtn();
});

      

Alternatively, you can add a class to buttons and use a class selector :

$('.extend-time').click(function () {
    SetTimeextendBtn();
});

      

As mentioned earlier, you don't need an anonymous function wrapper if you just call the function:

$('.extend-time').click(SetTimeextendBtn);

      

+1


source







All Articles