Note that there are some explanatory texts on larger screens.

plurals
  1. POUse Javascript / JQuery to dynamically create multiple HTML buttons with different click event handlers
    primarykey
    data
    text
    <p>I am trying to use Javascript / JQuery to dynamically create several HTML buttons, each of which does something different when it is clicked.</p> <p>My first attempt looked like this:</p> <pre><code>function myFunc( target_div, num_buttons ) { var buttons=""; for ( var i=0; i&lt;num_buttons; i++ ) { buttons += '&lt;input type="button" id="button_'+i+'" value="button_'+i+'"&gt;&lt;/input&gt;'; } target_div.html( buttons ); var doButtonPress = function( i ) { alert( i ); // I actually do something more complicated here, but it's not important now } for ( var i=0; i&lt;num_buttons; i++ ) { $('#button_'+i).click( function() { doButtonPress(i); } ); } } </code></pre> <p>Unfortunately this doesn't work because (I think) when the click event happens, doButtonPress is always passed the current value of i in myFunc's scope, not - as I intended - the value i had when the click event was defined. Thus the value passed to doButtonPress is always equal to num_buttons regardless of which button is pressed. So I then tried this instead:</p> <pre><code>$('#button_'+i).click( new Function( "doButtonPress("+i+");" ) ); </code></pre> <p>Unfortunately this doesn't work either - I get a message "ReferenceError: Can't find variable: returnResult". I assume that's because the Function constructor's arg value isn't parsed until the click event happens, and at that time I'm already outside of myFunc's scope so doButtonPress is undefined? Am I getting this right so far?</p> <p>So ... what do I do? :-)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload