2

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 .

2 Answers 2

6

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>');
Sign up to request clarification or add additional context in comments.

2 Comments

Thnxs for ur reply .... but am getting "callme is not defined" while i had defined callme function as" function callme() { alert("wed"); } " before writing the html line . ...... any suggestion where i am doing mistake @petr
@user1260967: I'd love to help you further but this piece of code you provided doesn't show anything that might potentionally go wrong. Something else is happening down the lines, try to edit your post for showing us more.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.