Advertisement
Advertisement


onclick event not working in JavaScript


Question

I have some JavaScript code in an HTML page with a button. I have a function called 'click()' that handles the onClick event of the button. The code for the button is as follows:

<input type="button" onClick="click()">button text</input>  

The problem is that when the button is clicked, the function is not called. What am I doing wrong here?
Thanks

2011/03/28
1
55
3/28/2011 1:57:57 AM

Accepted Answer

Two observations:

  1. You should write

    <input type="button" value="button text" />
    

    instead of

    <input type="button">button text</input>
    
  2. You should rename your function. The function click() is already defined on a button (it simulates a click), and gets a higher priority then your method.

Note that there are a couple of suggestions here that are plain wrong, and you shouldn't spend to much time on them:

  • Do not use onclick="javascript:myfunc()". Only use the javascript: prefix inside the href attribute of a hyperlink: <a href="javascript:myfunc()">.
  • You don't have to end with a semicolon. onclick="foo()" and onclick="foo();" both work just fine.
  • Event attributes in HTML are not case sensitive, so onclick, onClick and ONCLICK all work. It is common practice to write attributes in lowercase: onclick. note that javascript itself is case sensitive, so if you write document.getElementById("...").onclick = ..., then it must be all lowercase.
2011/03/28
112
3/28/2011 5:28:30 AM

click() is a reserved word and already a function, change the name from click() to runclick() it works fine

2011/07/22

Try this

<input type="button" onClick="return click();">button text</input>  
2011/03/28

Check you are calling same function or not.

<script>function greeting(){document.write("hi");}</script>

<input type="button" value="Click Here" onclick="greeting();"/>
2018/12/12

Try fixing the capitalization. onclick instead of onClick

Reference: Mozilla Developer Docs

2011/03/28

I suggest you do: <input type="button" value="button text" onclick="click()"> Hope this helps you!

2012/12/09

Source: https://stackoverflow.com/questions/5453937
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]