I have problem with adding event to button element.
Problem:
Function supposed to be event handler fires on page reload and when I click button.
I want it to fire only when button is clicked.
This is my code:
index.html file:
<form id="contact_form">
(Some form fields here)
<button id="form_submit" value="send">Send</button>
</form>
<script src="contact_form.js"></script>
contact_form.js file:
var submit_button = document.getElementById('form_submit');
submit_button.addEventListener("click", test_click_event());
function test_click_event()
{
alert("Button clicked");
}
I'm using Chrome to debug.
I have problem with adding event to button element.
Problem:
Function supposed to be event handler fires on page reload and when I click button.
I want it to fire only when button is clicked.
This is my code:
index.html file:
<form id="contact_form">
(Some form fields here)
<button id="form_submit" value="send">Send</button>
</form>
<script src="contact_form.js"></script>
contact_form.js file:
var submit_button = document.getElementById('form_submit');
submit_button.addEventListener("click", test_click_event());
function test_click_event()
{
alert("Button clicked");
}
I'm using Chrome to debug.
Share Improve this question edited Nov 9, 2019 at 15:59 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 9, 2013 at 14:28 KamilKamil 14k25 gold badges101 silver badges201 bronze badges 6-
1
Why not just use
onClick
instead? – pattyd Commented Jul 9, 2013 at 14:30 -
@pattyd You mean onClick event instead of Click, or adding
<button onClick="somefunction();">
in HTML? – Kamil Commented Jul 9, 2013 at 14:37 - yes that is what I mean... it would be so much easier – pattyd Commented Jul 11, 2013 at 14:56
- I still dont know what you meant. Read my ment again, I asked "something or something" :) – Kamil Commented Jul 12, 2013 at 1:02
- If you mean adding event inside html tag - I just want to keep js totally separated from HTML. – Kamil Commented Jul 12, 2013 at 1:03
3 Answers
Reset to default 4submit_button.addEventListener("click", test_click_event);
brackets are not needed
() brackets call to function execute remove them or use this:
var submit_button = document.getElementById('form_submit');
submit_button.addEventListener("click", function(){test_click_event();});
function test_click_event()
{
alert("Button clicked");
}
Demo
You can keep the brackets but you need to add an anonymous function. See here: https://www.w3schools./jsref/met_document_addeventlistener.asp
For example:
submit_button.addEventListener("click", function (){
test_click_event();
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744264085a4565780.html
评论列表(0条)