Jquery submit function not validating - javascript

So I have been working on a simple script for a class project. I am a new javascript student so this i giving me a hard time even though I think it can be solved easy. We the form is submitted, I input a 7 and get "wrong answer" which is good, but then I input 8 (correct answer) and it still outputs wrong answer. I do not know why it cannot differentiate any other number from 8. Please help
$("#story").submit(function (e) {
var answer = document.getElementById('human-story');
if (answer != 8) {
console.log(answer);
e.preventDefault();
}else {
alert("right answer");
e.preventDefault();
}
})
<form class="form-horizontal contact" name="contact" method="post" action="" id="story">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4>We are excited to hear your story!</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="contact-name" class="col-lg-2 control-label">Name:</label>
<div class="col-lg-10">
<input type="text" name="first_name" class="form-control" id="contact-name" placeholder="First & Last Name" required="" >
</div>
</div>
<div class="form-group">
<label for="contact-email" class="col-lg-2 control-label">Email:</label>
<div class="col-lg-10">
<input type="email" name="email" class="form-control" id="contact-email" placeholder="you#example.com" required="">
</div>
</div>
<div class="form-group">
<label for="contact-message" class="col-lg-2 control-label">Story:</label>
<div class="col-lg-10">
<textarea name="message" rows="8" class="form-control" style="resize:none;" required=""></textarea>
</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-2 control-label">5 + 3 = ?</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="human-story" name="human-story" placeholder="Your Answer" required="">
</div>
</div>
</div>
<div class="modal-footer">
Close
<button class="btn btn-success" name="submit-story" type="submit-story" value="Send!">Send</button>
</div>
</form>

You have more than one field with .form-controll class. Use id attribute to define which field have to be checked for the right answer:
$("#story").submit(function (e) {
e.preventDefault();
if ($("#human-story").val() == '8') {
alert("right answer");
} else {
alert("wrong answer");
}
});
Having multiple elements with form-controll class, using $(".form-controll").val() , jQuery returns value of the very first element with given class (in your case it's "name" field value).

use like this
$("#story").submit(function (e) {
if ($(".form-control").val() == '8') {
alert("right answer");
}else {
alert("wrong answer");
}
e.preventDefault();
});

first you can put e.preventDefault(); directly before you're setting the variable.
so you just have to write it once.
and y you don't just turn the if clause to
$("#story").submit(function (e) {
e.preventDefault();
var answer = parseInt($(".form-control").val(), 10);
if (answer == 8) {
alert("right answer");
} else {
alert("wrong answer");
}
});
see working fiddle:
$("#story").submit(function(e) {
e.preventDefault();
var answer = parseInt($(".form-control").val(), 10);
if (answer == 8) {
alert("right answer");
} else {
alert("wrong answer");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="story">
<input name="form--control" type="text" class="form-control" />
<input name="submit" type="submit" class="form--submit" />
</form>

Related

Focus event not working in HTML form

My HTML code is
<body>
<form name="contactus" id='contactus' action="test1.php" method="post" enctype="multipart/form-data">
<input type="hidden" value="2" name="Tab" id="Tab">
<div class="row underlinDv">
<div class="col-sm-4">
Your Email :
</div>
<div class="col-sm-8">
<input maxlength="100" type="email" class="form-control" placeholder="Enter Email" name="UEmailLogin" id="UEmailLogin" minlength="3">
</div>
</div>
<!--18-->
<div class="row underlinDv">
<div class="col-sm-8 col-md-offset-4">
<input type="submit" id="demo2GetTags" class="btn btn-primary btn-md" value="Submit" onclick='search()' />
</div>
</div>
</form>
<script>
function search() {
var Tab = document.getElementById("Tab").value;
alert(Tab);
var Eamillogin = document.getElementById("UEmailLogin").value;
if (Eamillogin == "") {
alert("please enter email");
Eamillogin.focus();
}
}
</script>
</body>
When I click on submit button, JavaScript alert shows "please enter email". It works fine. But Eamillogin.focus(); not working. After showing alert, the form automatically direct to test1.php page.Pointer not focus on Email. How to correct it?
Eamillogin variable contains the value of the #UEmailLogin element.
To set the focus on the element, use element.focus();
Here's updated code
var Eamillogin = document.getElementById("UEmailLogin"); // Removed .value from here
if (Eamillogin.value === "") { // Added .value here
alert("please enter email");
Eamillogin.focus(); // Focus element
}
function search() {
var Tab = document.getElementById("Tab").value;
var Eamillogin = document.getElementById("UEmailLogin");
if (Eamillogin.value === "") {
alert("please enter email");
Eamillogin.focus();
}
}
<form name="contactus" id='contactus' action="test1.php" method="post" enctype="multipart/form-data">
<input type="hidden" value="2" name="Tab" id="Tab">
<div class="row underlinDv">
<div class="col-sm-4">
Your Email :
</div>
<div class="col-sm-8">
<input maxlength="100" type="email" class="form-control" placeholder="Enter Email" name="UEmailLogin" id="UEmailLogin" minlength="3">
</div>
</div>
<!--18-->
<div class="row underlinDv">
<div class="col-sm-8 col-md-offset-4">
<input type="submit" id="demo2GetTags" class="btn btn-primary btn-md" value="Submit" onclick='search()' />
</div>
</div>
</form>

Validation check mark right beside form input field by jquery

There is a form on my page where I want to display a check mark(tick) right beside all input fields. I've already tried a couple of ways to do this but unable to achieve what I want.Below is my code....
$(document).ready(function() {
$("#myForm").on('submit', function(event) {
event.preventDefault();
var firstName = $('#first').val();
var lastName = $('#last').val();
var email = $('#email').val();
var pass = $('#password').val();
if (firstName == "") {
$('#first-name-error').text("Please enter your first name");
} else if (firstName.length > 0) {
$(this).next().show();
}
if (lastName == "") {
$('#last-name-error').text("Please enter your last name");
}
if (email == "") {
$('#email-error').text("Please enter your email address");
} else if (email == "aisha_salman3#outlook.com") {
$('#email-error').text("This email is already taken!");
}
if (pass == "") {
$('#password-error').text("Please enter your password");
} else if (pass.length < 8) {
$('#password-error').text("Short passwords are too easy to guess.Try one with at least 8 characters");
}
});
});
.tick {
background: url(images/done-tick.png) no-repeat;
width: 20px;
height: 20px;
position: absolute;
margin: 5px 20px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-3">
<form id="myForm" action="" method="">
<fieldset>
<legend>Create Account</legend>
<div class="form-group">
<label for="first">First Name</label>
<p id="first-name-error"></p>
<input type="text" class="form-control" id="first" maxlength="10" placeholder="your first name ..." autofocus />
<span class="tick"></span>
</div>
<div class="form-group">
<label for="last">Last Name</label>
<p id="last-name-error"></p>
<input type="text" class="form-control" id="last" maxlength="10" placeholder="your last name ..." />
<span class="tick"></span>
</div>
<div class="form-group">
<label for="email">Email</label>
<p id="email-error"></p>
<input type="email" class="form-control" id="email" placeholder="your email ..." />
<span class="tick"></span>
</div>
<div class="form-group">
<label for="password">Password</label>
<p id="password-error"></p>
<input type="password" class="form-control" id="password" placeholder="your password ..." />
<span class="tick"></span>
</div>
</fieldset>
<input class="btn" type="submit" value="Sign Up " />
</form>
</div>
</div>
</div>
</main>
Please guide me.Thank you!
You seem to be referencing this, which is the form element, not the first name. So when you get next, you are not getting an element. Your code should look like:
if (firstName == "") {
$('#first-name-error').text("Please enter your first name");
} else if (firstName.length > 0) {
$('#first').next().show();
}
Here is a fiddle to show how it works. https://jsfiddle.net/ukg82xqr/2/

Javascript not working properly on button

I have created a web page using bootstrap. There are 2 text boxes and a button to submit. I have written JavaScript function to give an alert if any text field is empty. I am amazed to see that it is not working. My JavaScript function is:
function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
return false;
}else if (a==null || a=="")
{
alert("Field 1 is required");
return false;
}else if (b==null || b=="")
{
alert("Field 2 is required");
return false;
}else if(a!="" && b!="")
{
alert("Submitted Successfully");
return true;
}
}
My form code is:
<form role="form" method="post" name="Form" onsubmit="return validateForm()">
<div class="row 150%">
<div class="6u 12u$(medium)">
<input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
</div>
<div class="6u 12u$(medium)">
<input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
</div>
</div><br /><br />
<button id="submit" class="button" style="vertical-align:middle">
<span>Submit </span>
</button>
</form>
How have you included the validateForm javascript?
for instance the following works for me:
<html>
<body>
<script>
function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
return false;
}else if (a==null || a=="")
{
alert("Field 1 is required");
return false;
}else if (b==null || b=="")
{
alert("Field 2 is required");
return false;
}else if(a!="" && b!="")
{
alert("Submitted Successfully");
return true;
}
}
</script>
<form role="form" method="post" name="Form" onsubmit="return validateForm()">
<div class="row 150%">
<div class="6u 12u$(medium)">
<input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
</div>
<div class="6u 12u$(medium)">
<input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
</div>
</div><br /><br />
<button id="submit" class="button" style="vertical-align:middle">
<span>Submit </span>
</button>
</form>
</body>
</html>

Error message in contact form

I have created a contact (4 input text) form and I want if user doesn't text in anyone of input a text message will appear above each input.
Contact From:
<form class="form-horizontal" method="post" action="#" name="form" onsubmit="return validation();">
<fieldset>
<div><h2 style="font-family: Myriad Pro;color:#7f8c8c">form</h2></div>
<div class="form-group">
<div class="col-sm-8">
<input id="fname" name="name" type="text" placeholder="Όνομα" class="form-control">
<div id="error1" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input id="lname" name="surname" type="text" placeholder="Επώνυμο" class="form-control">
<div id="error2" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 ">
<input id="email" name="email" type="email" placeholder="E-mail" class="form-control">
<div id="error3" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 ">
<textarea id="message" name="message" type="text" placeholder="Το σχόλιο σας.." columns="7" rows="7" class="form-control" style="background-color:#e5e6e6;" required=""></textarea>
<div id="error4" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-3 text-center">
<button type="submit" class="btn btn-primary btn-block" id="label" >SEND</button>
</div>
</div>
</fieldset>
</form>
And the script I use:
function validation(){
if (document.form.name.value == "") {
document.getElementById('error1').innerHTML="*Error Msg1 ";
}else if (document.form.surname.value == "") {
document.getElementById('error2').innerHTML="*Error Msg2 ";
}else if (document.form.email.value == "") {
document.getElementById('error3').innerHTML="*Error Msg3 ";
}else if (document.form.message.value == "") {
document.getElementById('error4').innerHTML="*Error Msg4 ";
}
return false;
}
My issue is that if for example the user doesn't fill his name(error message displayed below the text field) BUT then if he text his name the error message IS still displayed.How can I solve this?
There is an example here: Fiddle
I would suggest that you clear the error message at the start of the validation again:
function validation(){
document.getElementById('error1').innerHTML=""
document.getElementById('error2').innerHTML=""
document.getElementById('error3').innerHTML=""
document.getElementById('error4').innerHTML=""
//Your validation code below:
...
}
This way whenever the input validates, all of the error messages will be cleared and evaluated again.
You might want to consider storing the labels at the start of the function in a field so you have easy access to them later. This should help with readability as well. For example:
function validation(){
var errorMessage1 = document.getElementById('error1');
//Access the label using your new variable:
errorMessage1.innerHTML = "Your value here"
...
On keyup event lets try resetting the error message
document.form.name.addEventListener("keyup", function(){
document.getElementById('error1').innerHTML = '';
});

How to submit form if validate using jquery?

I am validating form with jquery. So when form submit i am using event.preventDefault(); after validate form , form will be submit to respective action page.But in my case it doesn't work.
Code what i did-
$('form[name=contact_form]').submit(function(event) {
event.preventDefault();
var formData = $('form[name=contact_form]').serialize();
var phone = $.trim($('form[name=contact_form]').find('input[name=PHONE]').val()).length;
var intRegex = /[0-9 -()+]+$/;
var alert = $('#contact_alert');
var success = $('#contact_success');
if(phone==0){
phone.focus();
alert.html("<p class='alert alert-danger' style='text-align:left;'>Phone number is required</p>");
}
else if((phone < 10)){
phone.focus();
alert.html("<p class='alert alert-danger' style='text-align:left;'>Please enter a valid phone number</p>");
return false;
}else{
return true;
}
});
Html Page :
<?php
echo form_open_multipart('home/inquiry', array('name' => 'contact_form'));
?>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="hidden" name="form_type" value="C">
<input type="text" name="NAME" id="user-name" class="form-control" placeholder="Full Name"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" name="PHONE" id="user-phone" class="form-control" placeholder="Phone"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" name="EMAIL" id="user-email" class="form-control" placeholder="Email"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" name="SUBJECT" id="user-subject" class="form-control" placeholder="Reason for inquiry"/>
</div>
</div>
<div class="col-md-12">
<textarea class="form-control" name="MESSAGE" id="user-message" placeholder="Message"></textarea>
</div>
<div class="col-md-12 text-left">
<div class="form-group">
<input type="submit" name="submit" class="btn btn-warning">
</div>
</div>
</div>
<?php echo form_close(); ?>
Do not call event.preventDefault(); if you want the form to be submitted after it validates ok.
Returning false after failed validation is enough.
$(this).submit();
When it's valid.
Try to replace the return true; for $(this).submit();
I usually do something like
$("#submit").submit(function(e){
if(validateFields() == true){ //If all fields are valid
$("#submit").submit();
}
else{
e.preventDefault(e);
}
});

Categories