Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have written following Javascript code.
JavaScript
<body>
    <script>
        function hi(){
           alert("Hello World !!");
        }

        var no1 = document.createElement('input');
        no1.setAttribute('type', 'button');
        no1.setAttribute('name', 'one');
        no1.setAttribute('value', '1');
        document.body.appendChild(no1);
    
        no1.onClick = hi;
    
    </script>
</body>


I have registered my event with the function hi(), but it is not working.
Is there any error in my code?

I would like that whenever I click on my button, it show me the alert box.

Thanks!
Posted
Updated 24-Dec-12 8:13am
v5

You never tried to create a single attribute responsible for events, which in this case should be onclick attribute: http://www.w3schools.com/jsref/event_onclick.asp[^].

But you don't have to add the attribute explicitly with setAttribute. It could be just
JavaScript
no1.onclick=function(){
   // some JavaScript code...
};


Good luck,
—SA
 
Share this answer
 
v2
The problem is, tat this way the generated code looks like this:
HTML
<input submitname="one" type="button" onclick="function hi(){ alert(" hello="" world="" value="1" />

I suppose, this is not what you want :)
You know why? Because of the capital letter: no1.onClick = hi;
Just make it lowercase and will work (no1.onclick = hi;).
 
Share this answer
 
You can make a asp.net object button or image button, and add the attribute onClientClick

So you make the button, press F4, in the property onClientClick enter "hi(); return false;" without the double quotes.

return false cancels the button postback event. You can do return hi();

and if hi returns true, the postback event fires, and if hi() returns false, the postback is canceled.

Just remember to register your java script file first.

[EDIT]
To fix your code above, you need to create the element correctly first for it to work. Don't use setAttribute, JavaScript has everything you need to build the element.

var inputObj = document.createElement ("input");
inputObj.type = "button"

<head>
    <script type="text/javascript">
        function AddButton () {
            var button = document.createElement ("input");

            button.type = "button";
            button.value = "Create a new button";
            button.onclick = AddButton;

            var container = document.getElementById ("buttonContainer");
            container.appendChild (button);
        }
    </script>
</head>
<body onload="AddButton ()">
    <div id="buttonContainer"></div>
</body>


http://help.dottoro.com/ljxhibki.php[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900