Skip to content Skip to sidebar Skip to footer

Bind Function To The Event "onclick" Of The Elements Of An Array Of Buttons

Preamble: I'm Italian, sorry for my bad English. This is my problem: I want to assign a function to a set of buttons. I need to send a parameter to the function. this is the code t

Solution 1:

buttons[i].onClick(sayHello(atxt));

Supposed to be

$(buttons[i]).on('click', function() { sayHello(atxt) });

If you want to get the current button id then I think you are looking for this..

for (var i = 0; i < buttons.length; i++) {
     $(buttons[i]).on('click', function() { sayHello(this.id) });
}

Solution 2:

If you want to iterate through all of the buttons then you have to do that with .each() handler of the jquery:

$(function(){
  $(".tblButton").each(function () {
    $(this).click(function(){
       alert($(this).attr('id'));
    }); 
  });
});

checkout the jsbin: http://jsbin.com/usideg/1/edit

Solution 3:

Would this not work for your example: Do you have another reason for the iteration?

functiontest(atxt) {
    $('.tblButton').on('click',function(){sayHello(atxt);});
}

functionsayHello(txt){alert('hello' + txt)};

OR optionally if the elements are static and present:

function test(atxt) {
    $('.tblButton').click(function(){sayHello(atxt);});
}

function sayHello(txt){alert('hello' + txt)};

Alternate approach: just change to this style:

var txt = "fred";
var atext = "hello" + txt;

functionsayHello(atext) {
    alert(atext);
}
$('.tblButton').on('click', function() {
    sayHello(atext);
});
//below here just to demonstrate
$('.tblButton').eq(0).click();//fires with the fred
txt = "Johnny";// new text
atext = 'hello' + txt;
$('.tblButton').eq(1).click();//fires the Johnny

see it working here: http://jsfiddle.net/dFBMm/

SO based on your note: this markup and code:

<button class="tblButton" id="Ruth">Hi</button>
<buttonclass="tblButton"id="Betty">Hi again</button>

$('.tblButton').on('click', function() {
    alert("Hello "+$(this).attr("id"));
});
$('.tblButton').eq(0).click();//fires with the Ruth
$('.tblButton').eq(1).click();//fires the Betty

http://jsfiddle.net/dFBMm/1/

Post a Comment for "Bind Function To The Event "onclick" Of The Elements Of An Array Of Buttons"