<html>
<body>
<form onsubmit="return myFunction()">
<input type="text" id="txt">
<input type="text" id="txt1">
<input type="button" value="click" id="btn">
</form>
</body>
<script>
var a = document.getElementById("txt");
var b = document.getElementById("txt1");
var save = document.getElementById("btn");
//save.addEventListener("click" , myFun);
save.onclick = function(){myFunction()};
//save.addEventListener("click" , myFunction);
function myFunction(){
if((a.value=="") || (b.value=="")){
alert("fill something");
return false;
}else{
alert("all ok");
location.href="sec.html";
return true;
}
//a.addEventListener("keyup" , myFun);
//b.addEventListener("keyup" , myFun);
}
a.addEventListener("keyup" , myKeyFun);
b.addEventListener("keyup" , myKeyFun);
function myKeyFun()
{
if(a.value!==b.value){
alert("mismatched");
return false;
}else{
return true;
}
}
</script>
</html>
i have created many function for different - different validation so now i want to submit the form and redirect to another page when all the cinditons are true. but here form is getting submitted even when the conditions are not true, i have wrote this code just to understand. the actual code is quite big so i have wrote this to understand how i would have to call the main function to submit the form when there is multilpe function
Don't mess by making different functions. Do it with conditions as below.
var a = document.getElementById("txt"); var b = document.getElementById("txt1"); var save = document.getElementById("btn"); function myFunction() { if(a.value == ""){ alert("Please fill Text 1"); }else if(b.value == ""){ alert("Please fill Text 2"); }else if (a.value != b.value){ alert("Text 1 and Text 2 must be same"); } else{ alert("Successfully submitted"); //redirect to another page code; } } function textTwoFun(){ if(a.value != b.value){ alert('Value missmatched! Text 1 and Text 2 must be same'); } }
<form> <input type="text" id="txt" placeholder="Text 1"> <input type="text" id="txt1" onkeyup="textTwoFun()" placeholder="Text 2"> <input type="button" onclick="myFunction()" value="click" id="btn"> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.