How to execute Jquery onclick="" function only after JS validation - javascript

I wonder if I can execute onlick function only after JS validation any ideas?
I have a form which has e-amil and phone mandatory filed and i would like to check them before form is submitted , even more if everything is ok another div onclick="$('#dialog-links-blocks').show()" should be display with a message Thank you! How can I make it to be shown only after validation !
<script type="text/javascript">// <![CDATA[
function validateForm()
{
var x=document.forms["myform"]["phone"].value;
var y=document.forms["myform"]["email"].value;
if (x==null || x=="")
{
alert("Укажите номер телефона!");
return false;
}
if (y==null || y=="")
{
alert("Укажите email!");
return false;
}
}
// ]]></script>
<iframe name="hiddenFrame" width="320" height="240"></iframe>
<form id="validation" action="http://listovki.md/send_form_email.php" method="POST" name="myform" enctype="multipart/form-data" onsubmit="return validateForm()" target="hiddenFrame">
<table><colgroup> <col width="122" /> <col width="260" /> </colgroup>
<tbody>
<tr>
<td><label>имя</label></td>
<td><input type="text" name="family" /></td>
</tr>
<tr>
<td><label>почта</label></td>
<td><input type="email" name="email" /></td>
</tr>
<tr>
<td><label>gsm</label></td>
<td><input class="gsm" type="tel" name="phone" /></td>
</tr>
<tr>
<td colspan="2"><input class="aplicaAcumBt" onclick="$('#dialog-links-blocks').show()" type="submit" name="submit" value="отправить" /></td>
</tr>
</tbody>
</table>
</form>

Why not show div only if validation is true? why show only on click
<script type="text/javascript">// <![CDATA[
function validateForm()
{
var x=document.forms["myform"]["phone"].value;
var y=document.forms["myform"]["email"].value;
if (x==null || x=="")
{
alert("Укажите номер телефона!");
return false;
}
if (y==null || y=="")
{
alert("Укажите email!");
return false;
}
// Validation is true here
$('#dialog-links-blocks').show()
}
</script>

Related

Don't send form data when to type no in confirm window

Type apple in the input whose name is goods,and type 9 in the input whose name is price,and click submit,now confirm window pop up,whatever your click yes or no,the data will send to price.php.
My expectation:
when you click yes ,the data will send to price.php,
when you click no ,the data will not send to price.php,what's wrong for my js?
ob = document.getElementById("submit");
function check(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
exit;
}
}
}
ob.addEventListener("click",check,false);
<form action="price.php" method="post">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
The price.php is simple.
<?php
var_dump($_POST);
?>
The exit below can't prevent form data from sending to price.php.
if(flag){
return true;
}else{
exit;
}
It is no use either to change exit; into return false;.
It is no use either to change js into below.
ob = document.getElementById("submit");
function check(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
exit;
}
}
}
ob.addEventListener("submit",check,false);
The traditional way is same as The KNVB did,the key point is <form action="price.php" method="post" onsubmit="return check()"> ,to bind form's attribute onsubmit with function check.
DOM0 level event way,almost the same like the traditional way.
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('submit');
ob.onclick =function(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
return false;
}
}
}
</script>
</body>
</html>
What OP expect is the DOM2 level event way.
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('submit');
function check(event){
console.log(ob.type);
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
ob.submit();
return true;
}else{
event.preventDefault();
return false;
}
}
}
ob.addEventListener("click",check);
</script>
</body>
</html>
The key points in DOM2 level event way are:
1.when flag is true
if(flag){
ob.submit();
return true;
}
2.when flag is false
else{
event.preventDefault();
return false;
}
This is my solution:
<html>
<body>
<form action="price.php" method="post" onsubmit="return check()">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
function check()
{
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
return false;
}
}
}
</script>
</body>
</html>
I tested it on Edge, IE11, Firefox, chrome browser, it works.
I found another solution:
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('form');
function check(event){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
ob.submit();
return true;
}else{
event.preventDefault();
return false;
}
}
}
ob.addEventListener("submit",check);
</script>
</body>
</html>
A couple of things about the code:
exit - I've never seen before - is it javascript?
document.getElementById('price').value - returns a string - you should parse it (to a number) before comparing.
Use onsubmit="" attribute of the form - return true to allow form submission, false to block submission.
window.confirm already returns a boolean, just return that (instead of if statement).
Here's a bare-bones example:
function validate() {
const price = parseFloat(document.getElementById('price').value)
if (price < 10) {
return window.confirm("Are your sure the price is less than 10 ?")
}
return true // <- otherwise allow form submission
}
<form action="price.php" method="post" onsubmit="return validate()">
<input type="text" id="price" name="price">
<input type="submit" id="submit" value="submit">
</form>
Also, in general, try to condense your problem to the minimum code required to reproduce an issue.

Form not submitting after validation

Good evening,
I currently have a HTML Form with a script to validate the field have data entry into them however after it validating all fields are filled it doesnt submit, can anybody please advise what is wrong? New to this so learning and would really appreciate any help possible.
I have attached the code im using below.
<div id="form">
<form name="contact" method="post" action="contact.php" onsubmit="return !!(validatename()&validateemail()&validatecomments()&validateRecaptcha());">
<table width="450px">
<tr>
<td valign="top"><label for="name">Name</label></td>
<td valign="top"><input type="text" name="name" maxlength="50" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="email">Email Address</label></td>
<td valign="top"><input type="text" name="email" maxlength="80" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="comments">Comments</label></td>
<td valign="top"><textarea name="comments" maxlength="1000" cols="32" rows="8"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<div id="form" class="g-recaptcha" data-sitekey="6LdcZFkUAAAAAFoHAYtupqKzCgd2T9XzHZFj8XNw"></div>
<input type="image" src="images/submit.png" alt="Submit">
</td>
</tr>
</table>
</form>
<script>
function validatename()
{
if( document.contact.name.value == "" )
{
alert( "Please provide your name!" );
document.contact.name.focus() ;
return false ;
}
}
function validateemail()
{
if( document.contact.email.value == "" )
{
alert( "Please provide your email address!" );
document.contact.email.focus() ;
return false ;
}
}
function validatecomments()
{
if( document.contact.comments.value == "" )
{
alert( "Please provide your comments!" );
document.contact.comments.focus() ;
return false ;
}
}
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("You need to fill the captcha");
return false ;
}
}
</script>
This is one way how you could do it:
function validatename() {
if (document.contact.name.value == "") {
alert("Please provide your name!");
document.contact.name.focus();
return false;
}
else {
return true;
}
}
function validateemail() {
if (document.contact.email.value == "") {
alert("Please provide your email address!");
document.contact.email.focus();
return false;
}
else {
return true;
}
}
function validatecomments() {
if (document.contact.comments.value == "") {
alert("Please provide your comments!");
document.contact.comments.focus();
return false;
}
else {
return true;
}
}
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("You need to fill the captcha");
return false ;
}
else {
return true;
}
}
document.getElementById('my-form').addEventListener('submit', function(e) {
e.preventDefault();
if (validatename() && validateemail() && validatecomments() && validateRecaptcha()) {
var formValidation = true;
}
else {
var formValidation = false;
}
if (formValidation) {
this.submit();
}
});
<div id="form">
<form id="my-form" name="contact" method="post" action="contact.php">
<table width="450px">
<tr>
<td valign="top"><label for="name">Name</label></td>
<td valign="top"><input type="text" name="name" maxlength="50" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="email">Email Address</label></td>
<td valign="top"><input type="text" name="email" maxlength="80" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="comments">Comments</label></td>
<td valign="top"><textarea name="comments" maxlength="1000" cols="32" rows="8"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<div id="form" class="g-recaptcha" data-sitekey="6LdcZFkUAAAAAFoHAYtupqKzCgd2T9XzHZFj8XNw"></div>
<input type="image" src="images/submit.png" alt="Submit">
</td>
</tr>
</table>
</form>
</div>
To make it work correctly, make sure that grecaptcha is defined.

Not able to submit the form using jquery

Hi i have login form page where i validated using jquery. jquery script is checking for null values but when i entered the values it is not submittingbut i am able to see the alerts in else block
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
//$(this).hide();
var name = $.trim($("#uname").val());
var pwd = $.trim($("#pwd").val());
alert("Value: " + name);
alert("Text: " + pwd);
if(name == ''){
alert('ssss');
$(":input").css({
"background-color":"#FFCECE",
"border":"1px solid red"
});
// return false;
$('form').submit(function(){
//e.preventDefault();
return false;
});
}else{
alert('else');
$(":input").css({
"background-color":"",
"border":""
});
alert('else2');
$('form').submit(function(){
alert("thanks");
return true;
});
alert('else3');
}
});
});
</script>
This is my Html code
<form action="" method="post" name="loginform">
<table>
<tr>
<th>LOGIN PAGE</th>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="uname" id="uname" /></td>
<tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd" id="pwd" /></td>
<tr>
<tr>
<td colspan="2"><input type="submit" name="submit" id="submit" value="SUBMIT" /> </td>
<tr>
</table>
</form>
Thanks in advance..
Instead of
$('form').submit(function(){
alert("thanks");
return true;
});
in your else, just return true;
same in your if, you don't need to
$('form').submit(function(){
//e.preventDefault();
return false;
});
just return true;
What you're doing in your code is hooking up to the submit event of the form. If you return false or true from submit button, it'll submit the form or not.

Javascript validation:

i am having this problem where those validation stopped working starting from the email validation part onwards.
i just couldn't figure out why even after days looking at it and just wondering if someone can point out my mistake here?
Javascript part:
function validateForm()
{
var x=document.forms["myForm"]["firstname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
var x=document.forms["myForm"]["lastname"].value;
if (x==null || x=="")
{
alert("Last name must be filled out");
return false;
}
var x=document.forms["myForm"]["age"].value;
if (x==null || x=="" || x < 18 || x > 110 || isNaN(x))
{
alert("Age must be 18-110");
return false;
}
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
var x=document.forms["myForm"]["phone"].value;
var pattern = /^\(?([0-9]{2})\)?[ ]+([0-9]{4})[ ]+([0-9]{4})$/;
if (x==null || x=="")
{
alert("Not a valid phone number");
return false;
} else if (x.match(pattern)) {
return true;
} else {
alert ("Phone number must be in the following format: xx xxxx xxxx");
return false;
}
}
and this is the form part:
<form id="myForm" action="../includes/create-user.php" onsubmit="return validateForm();" method="post">
<div id = "table">
<table>
<tr>
<td>First Name: </td>
<td><input type="text" name="firstname" id="firstname"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastname" id="lastname"/></td>
</tr>
<tr>
<td>Age: </td>
<td><input type="text" name="age" id="age"/></td>
</tr>
<tr>
<td>E-mail (username): </td>
<td><input type="text" name="user" id="user1"/></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="pass" id="pass1"/></td>
</tr>
<tr>
<td>Phone: </td>
<td><input type="text" name="phone" id="phone"/></td>
</tr>
</table>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Register"/>
</div>
</form>
The first thing that stands out is that you specify your field:
<td><input type="text" name="user" id="user1"/></td>
with id = 'user1'
and you look in your script for email
var x=document.forms["myForm"]["email"].value;

Check word length not working

HTML
<form name="f1" action="feedback1.php" method="Post" onSubmit="return isDataFilled();" >
<table border="0" align="center" width="500px" style="max-width: 500px;" cellspacing="3" cellpadding="5" align="center">
<tr align="left">
<td width="25%">
Enter your subject </td>
<td width="75%"><input type="text" name="subject" size="30" value="Your subject" onClick="if(this.value=='Your subject'){this.value=''}; this.style.backgroundColor='#CCFF99'" onBlur="if(this.value==''){this.value='Your subject'}; this.style.backgroundColor='white'"/></td>
</tr>
<tr align="left">
<td>
Enter your email<span style="color:#FF0000">*</span> </td>
<td>
<input type="text" name="email" size="30" value="example#mail.com" onClick="if(this.value=='example#mail.com'){this.value=''}; this.style.backgroundColor='#CCFF99'" onBlur="if(this.value==''){this.value='example#mail.com'}; this.style.backgroundColor='white'"/> </td>
</tr>
<tr align="left">
<td colspan="2">
Enter your message here<span style="color:#FF0000">*</span>: </td>
</tr>
<tr align="left">
<td colspan="2">
<textarea rows="10" cols="50" name="message" title="Your message goes here" onClick= "if(this.value=='Your message goes here'){this.value=''}; this.style.backgroundColor='#CCFF99'" onBlur="if(this.value==''){this.value='Your message goes here'}; this.style.backgroundColor='white'" >Your message goes here</textarea> </td>
</tr>
<tr>
<td colspan="" align="right">
<input type="submit" value="Send" name="b1" title="Send your message"/>
</td>
<td align="center">
<input type="reset" value="Reset" name="reset" title="Removes your form data and fill it again"/> </td>
</tr>
</table>
</form
JavaScript
function isDataFilled()
{
if(document.forms['f1']['email'].value=='example#mail.com')
{
alert("No email address in email field!");
return false;
}
if(document.forms['f1']['message'].value=='Your message goes here')
{
alert("No message in message field!");
return false;
}
return isEmailCorrect(document.forms["f1"]["email"].value);
return check_word_length(document.forms['f1']['message'].value, 20);
}
function isEmailCorrect(f_email)
{
var x=f_email;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
function check_word_length(text, over_size)
{
var word=0;
var message=text;
for(i=0;i<message.length;i++)
{
if(message.charAt(i)==" ")
{
word=0;
}
else
{
word++;
if(word>=over_size)
{
alert("Too long text entered");
return false;
}
}
}
}
The function check_word_length(text, over_size) is not working. I'm confused because I think my code is alright.
At the end of your isDataFilled:
return isEmailCorrect(document.forms["f1"]["email"].value);
return check_word_length(document.forms['f1']['message'].value, 20);
The return keyword immediately exits the current function; so the second return in that code will never be reached.
When you return a value in a function, it ends that function. So what is after that will not be called. So in this part:
return isEmailCorrect(document.forms["f1"]["email"].value);
return check_word_length(document.forms['f1']['message'].value, 20);
... the function will stops after isEmailCorrect call.
Plus, stop copy/paste codes from web and start try your own codes to know what you're doing.
I believe the issue is being caused by the fact that isDataFilled returns whatever isEmailCorrect() returns. Execution in the function stops there, so it never calls the last function

Categories