javascript to create a button with onclick
Asked Answered
R

3

16

I'm trying to use javascript to create a button that has a onclick event that calls a function defined in the head that takes in as parameter a dom object relative to the button. how do i do this?

ex:

<html>
<head> <script>function blah(obj){alert(obj.value)}</script></head>
<body>
<button onclick="blah(this.parentNode.value);"></button>
</body>
</html>

javascript:

var newButton = document.createElement("button");
???

in the end i want the new button to be the same as the existing one.

Retardment answered 28/12, 2011 at 1:34 Comment(2)
could you explain why you're doing this, perhaps a better solution exists for what you're doing..Brendon
its kinda (unnecesarily) complicated but i'll try. so the original button will create a bunch of stuff and delete itself. Among the created stuff is another button that will recreate the original button which could create another bunch of stuff and so onRetardment
B
38
function createButton(context, func) {
    var button = document.createElement("input");
    button.type = "button";
    button.value = "im a button";
    button.onclick = func;
    context.appendChild(button);
}

window.onload = function() {
    createButton(document.body, function() {
        highlight(this.parentNode.childNodes[1]);
        // Example of different context, copied function etc
        // createButton(this.parentNode, this.onclick);
    });
};

Is that what you want?

Brendon answered 28/12, 2011 at 1:38 Comment(5)
i dont think it solves the DOM problem where the argument passed in is relative to the button :(Retardment
@zaftcoAgeiha I have no idea what that means. Could you explain what you want please. Edit :: Check the post again.Brendon
ok i need to be able to dynamically create this <button onClick="highlight(this.parentNode.childNodes[1])">highlight</button> and have it clickableRetardment
i get the error "Uncaught TypeError: Cannot read property '1' of undefined". i think the problem is that javascript thinks that "this" refers to the js object as opposed to the html dom objRetardment
@zaftcoAgeiha It's possibly because I typed out 'childNotes' instead of 'childNodes'... The code works.Brendon
T
1

You can also use the built-in setAttrbute javascript function.

var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")

Hope it will help

Tow answered 4/7, 2020 at 13:7 Comment(0)
W
0

var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")
Wandawander answered 2/7 at 19:18 Comment(1)
Hi! If you meant to add additional information or a different perspective, you might want to edit your answer to clearly highlight your unique contribution because it appears to be very similar to the previous answer.Herodias

© 2022 - 2024 — McMap. All rights reserved.