Why functionToCallOnOk I pass to my function does not get called when I attach it to callback via jQuery?

Go To StackoverFlow.com

0

So I try such code:

function showAlertWithCallback(w, h, name, body_text, functionToCallOnOk) {
    prepareWindow();
    var ran_alert_number=Math.random()*50000;
    $("#alert_content").html(body_text + '<br/>' + '<input type=\"button\" class=\"eButton\" value=\"Cancel\" onClick=$(\".alert\").hide() />' + '<input id=\"general-alert-'+ ran_alert_number +'\" type=\"button\" class=\"eButton\" value=\"OK\" onClick=\"$(\'.alert\').hide();\"/>');
$('#general-alert-' + ran_alert_number).click(functionToCallOnOk);  
 // also tried $('#general-alert-' + ran_alert_number).click(function(){functionToCallOnOk();});
    showAlertBase(w, h, name);
}

called via something like:

showAlertWithCallback(
       600, 
       100 , 
       ('New name for to ' + file_title + ' file.'),
       '<input type="text" style="width:590px" class="text" value=\"' + file_title + '\">', 
       function(){
         alert("hi!");
       }
    );

runs with no errors (chrome debugger) but function does not get called on OK click. Why and how to fix such thing?

2012-04-04 23:22
by myWallJSON


3

Math.random()*50000 will produce a number like 38518.060150090605, which when you concatenate with '#general-alert-' in the jQuery call will produce a selector like this:

#general-alert-38518.060150090605

That will be treated as a selector which finds an element with id general-alert-38518 and class 060150090605, since the class name comes after the dot.

To make the random number, use, say, Math.floor(Math.random()*5000) instead.

A better option would be to use an incrementing global variable (eg, _global_counter++ each time you use it), then you would not have a chance of getting two elements with the same id.

An even better solution would be to create actual DOM elements in JavaScript, attach events to those elements, then insert those elements into the correct place in the document. That way they won't need to have ids at all.

2012-04-04 23:27
by Douglas
It worked!))) All forgot about using floor with id.. - myWallJSON 2012-04-04 23:37


0

Try removing the onClick attribute of the OK button.

2012-04-04 23:27
by Matt Bradley
Ads