Bounce
Bounce

Reputation: 2095

JavaScript dynamic parameters

I have following code (html,js,jquery) snippet (http://jsfiddle.net/MUScJ/2/):

<script type="text/javascript">
    function someFunc(){
    html = '';
    z = 1;
    for(i=0; i<5; i++){
        html += '<input type="button" value="Button_'+z+'"' +
                'onclick="otherFunc(z);">';
         z++;
    }

    $("#container").html(html);

   return true;
}

function otherFunc(z){
    alert('z:' + z);

     return true;   
}

</script>   

<div id="container"></div>
<input type="button" value="Go" onclick="someFunc();" />

This script outputs five buttons with onclick event. JS function otherFunc always returns z variable equal to 6. Is it possible to overcome this ? I want every button have its specific z value - 1,2,3.. and etc.

Any ideas ?

Upvotes: 0

Views: 393

Answers (5)

megas
megas

Reputation: 21791

<script type="text/javascript">
function someFunc(){
    html = '';
    z = 1;
    for(i=0; i<5; i++){
        html += '<input type="button" value="Button_'+z+'"' +
                'onclick="otherFunc(z);">';
         z++;
    }

    $("#container").html(html);

   return true;
}


function otherFunc(z) {
    return function() {
        alert('z:' + z);
    };
}

</script>    

<div id="container"></div>
<input type="button" value="Go" onclick="someFunc();" />

Upvotes: 0

Tadeck
Tadeck

Reputation: 137360

Yes, change this:

html += '<input type="button" value="Button_'+z+'"' +
    'onclick="otherFunc(z);">';

into this:

html += '<input type="button" value="Button_' + z + '"' +
    'onclick="otherFunc(' + z + ');">';

This issue is a result of the fact you iterate by incrementing z, but create code that uses z (whatever the value will be when invoked after creation - in this case it is 6) instead of using z to create static code (entering the value in the time of HTML creation).

Upvotes: 1

Matt Greer
Matt Greer

Reputation: 62027

Since you did not use var, your z variable is global. This is bad news for many reasons. But in your case, your onclick is calling otherFunc(z), where z is the global z which gets its final value of 6.

One possible fix is to change the html you generate:

var z = 1;
var html = '';
for(var i=0; i<5; i++){
    html += '<input type="button" value="Button_'+z+'"' +
            'onclick="otherFunc(' + z + ');">';
     z++;
}    

This is the simplest way to fix it, however you're not really taking advantage of the power that jQuery gives you.

Upvotes: 1

Jayendra
Jayendra

Reputation: 52779

Updated demo - http://jsfiddle.net/MUScJ/4/

Updated code -

    html += '<input type="button" value="Button_'+z+'"' +
            'onclick="otherFunc('+z+');">';

Upvotes: 3

ValeriiVasin
ValeriiVasin

Reputation: 8706

You are using string instead of param :) This is your updated example.

But try to replace onclick by jquery bind. Onclick is strongly not recommended for usage :)

Upvotes: 2

Related Questions