Reputation: 11
i have just started studying js with this js code
<div class="container">
<form name="myForm" action="#" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit" id="smit">
</form>
<script>
var smit=document.getElementById("smit");
smit.addEventListener("click",formvalidate(),false);
function formvalidate(){
console.log(" vua moi click submit");
if(t==null){
var t= document.forms["myForm"]["fname"].value;
if(t==null || t==""){
alert("xin dien vao email");
}
}
}
</script>
When previewing in browser, a alert popup auto appear despite i not click on submit button. Can anyone please explain me what happening? Thanks.
Upvotes: 1
Views: 22744
Reputation: 39270
I have made some little changes so it'll work in IE as well:
<form name="myForm" id="myForm" action="#" method="post">
First name: <input type="text" name="fname" id="fname">
<input type="submit" value="Submit" id="smit">
</form>
<script >
function formvalidate(event){
//removed console log because that only works in ie
// when debugging
var t= document.getElementById("fname").value;
if(t==""){
alert("xin dien vao email");
if(event.preventDefault){ event.preventDefault()};
if(window.event){window.event.returnValue = false;}
}
}
var smit=document.getElementById("myForm");
if(smit.addEventListener){
smit.addEventListener("submit",formvalidate,false);
}else{
//ie doesn't have addEventListner
smit.attachEvent('onsubmit', formvalidate);
}
</script>
Upvotes: 2
Reputation: 17655
Event listener does not contains parenthesis, removes it .if you add parenthesis to it , it looks like function but here you have to assign your eventlistener.
smit.addEventListener("click",formvalidate,false);
Upvotes: 0
Reputation: 100175
remove parenthesis from formvalidate, like:
smit.addEventListener("click",formvalidate(),false);
to
smit.addEventListener("click",formvalidate,false);
See: addEventListener
Upvotes: 1
Reputation: 219938
The parentheses after your function name causes the function to be called right away. Since you're just assigning it as the event listener, you want to pass it.
Remove the parentheses and it'll wait for the click before executing:
smit.addEventListener("click", formvalidate, false);
// ^^ No parentheses
Upvotes: 6