user1260967
user1260967

Reputation: 99

Calling function from button not working for html created using javascript

I am using javascript to create html page , but not able to call some function on button click .

var alernative = "plot1";
var buttonvalue= "mybutton";
 function callme()
 {alert("hello");}   

 $('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="' +   callme() + '";></div>');

In above code , creating a button and giving its value and calling function onclick of button , but when the page loads it shows alert (that should not happen) and it is not alerting on button click .

Hoping for Suggestion or some help .

Upvotes: 2

Views: 484

Answers (2)

Niccol&#242; Campolungo
Niccol&#242; Campolungo

Reputation: 12042

It is a bad practice to write HTML with strings, DOM exists for one reason!

var input = $('<input/>', {
    type: "button",
    style: "float: right",
    value: buttonValue
}),
    element = $('<div/>').append(input);
input.click(function () {
    callme();
});
$('#test').html(element);

Upvotes: 0

Petr Čihula
Petr Čihula

Reputation: 997

You need to pass the function name as a part of the string:

$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="callme();"></div>');

Upvotes: 6

Related Questions