Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript to create a button with onclick

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.

like image 230
WindowsMaker Avatar asked Dec 28 '11 01:12

WindowsMaker


People also ask

Can we add onclick to button?

The onclick attribute is an event attribute that is supported by all browsers. It appears when the user clicks on a button element. If you want to make a button onclick, you need to add the onclick event attribute to the <button> element.

How do I make a click button?

The <button> tag defines a clickable button. Inside a <button> element you can put text (and tags like <i> , <b> , <strong> , <br> , <img> , etc.). That is not possible with a button created with the <input> element!

How do you click a button in JavaScript?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.

Can we create button in JavaScript?

Creating button object: The button object can be created using JavaScript. The document. createElement() method is used to create <button> element. After creating a button object use appendChild() method to append the particular element (such as div) to display it.


1 Answers

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?

like image 190
AlanFoster Avatar answered Sep 24 '22 13:09

AlanFoster