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.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
WindowsMaker
  • 3,132
  • 7
  • 29
  • 46
  • could you explain why you're doing this, perhaps a better solution exists for what you're doing.. – AlanFoster Dec 28 '11 at 01:35
  • 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 on – WindowsMaker Dec 28 '11 at 01:45

2 Answers2

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?

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
AlanFoster
  • 8,156
  • 5
  • 35
  • 52
  • i dont think it solves the DOM problem where the argument passed in is relative to the button :( – WindowsMaker Dec 28 '11 at 01:44
  • @zaftcoAgeiha I have no idea what that means. Could you explain what you want please. Edit :: Check the post again. – AlanFoster Dec 28 '11 at 01:44
  • ok i need to be able to dynamically create this and have it clickable – WindowsMaker Dec 28 '11 at 02:05
  • 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 obj – WindowsMaker Dec 28 '11 at 02:39
  • @zaftcoAgeiha It's possibly because I typed out 'childNotes' instead of 'childNodes'... The code works. – AlanFoster Dec 28 '11 at 02:42
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