I'm new to Jquery and came across something I can not solve think I need someone who with a little more experience.
Form validation is not working correctly but works fine on jsfiddle.
Am I suppose to have document.ready ?
Any help would be great thanks
<script>
$('#add_film').submit(function (e) {
var error = false;
// No value for movie_title
if ($('#movie_title').val() == "") {
alert("No Film");
error = true;
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert("No actor");
error = true;
}
// No value for rating
if ($('#rating').val() == null) {
alert("No Rating");
error = true;
}
//No value for review
if ($('#review').val() == "") {
alert("No review");
error = true;
}
// Focus on first form field.
$("input:text:visible:first").focus();
if (error) {
e.preventDefault();
}
});
</script>
<form action="add_film.php" method="post" id="add_film">
<label for="title">Movie Title</label>
<input type="text" name="movie_title" id="movie_title" />
<br/>
<br/>
<label for="actor">Leading Actor</label>
<input type="text" name="leading_actor" id="leading_name" />
<br/>
<br/>
<label for="rating">Rating</label>
<select id="rating" name="rating"/>
<option selected="selected" value=0 disabled="disabled">Select a Rating</option>
<option value="Terrible">Terrible</option>
<option value="Fair">Fair</option>
<option value="Ok">Ok</option>
<option value="Good">Good</option>
<option value="Excellent">Excellent</option>
</select>
<br/>
<br/>
<label for="review">Your Review</label>
<br/>
<textarea name="review" id="review" rows="15" cols="60"></textarea>
<br/>
<br/>
<input type="submit" name="submit" id="submit" value="submit" />
<input type="hidden" name="submitted" value="TRUE" />
You had not closed your form tag, so the script doesn't work.
Here is the working code for you.
http://jsbin.com/EDOJEZ/1/edit?html,output
Yes!!! the code should be in document ready handler
jQuery(function($){
$('#add_film').submit(function (e) {
var error = false;
// No value for movie_title
if ($('#movie_title').val() == "") {
alert("No Film");
error = true;
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert("No actor");
error = true;
}
// No value for rating
if ($('#rating').val() == null) {
alert("No Rating");
error = true;
}
//No value for review
if ($('#review').val() == "") {
alert("No review");
error = true;
}
// Focus on first form field.
$("input:text:visible:first").focus();
if (error) {
e.preventDefault();
}
});
})
you please run your web page in google chrome and press ctrl+shift+j to open developer console. So that you could see the javascript/jquery errors with line numbers+preview there and try to resolve yourself. I promise, you can do it as simple.
Related
The following is a complete copy of the project I'm working on. I'm having problems with the JavaScript validating segments of the form as well as JavaScript producing an alert at the end of the function.
The idea is to have the functions is to validate the form so that, if you are over 18: you only need the first and last name fields filled out. (The content doesn't really matter so long as it works.) On the other hand however, if you are under 18, the function will need to validate guardian details as well.
Until somewhat recent changes were made however this worked fine, the problem is I left the project for several weeks so I don't know what changes were made to be able to undo them. Ideally the basic code wouldn't change too much, I'm looking for a quick fix or stop-gap measures that will have the same effect.
<html>
<head>
<meta charset="utf-8">
<title>Work Field Trip Registration</title>
<script type="text/javascript">
function HideReveal() {
if (document.getElementById("YesNo").selectedIndex == "1") {
document.getElementById("ifYes").style.display = "block";
Required();
//alert('1st Option Tested');
}
else if (document.getElementById("YesNo").selectedIndex == "0") {
document.getElementById("ifYes").style.display = "none";
Required();
//alert('2nd Option Tested');
}
}
function Required() {
if (document.getElementById("YesNo").selectedIndex == "1") {
AddRequirement();
//alert("Step1");
}
else {
NoRequirement();
//alert("Step2");
}
}
function NoRequirement() {
document.getElementById("GuardName").removeAttribute("required");
document.getElementById("GuardPhone").removeAttribute("required");
//alert("Step3");
}
function AddRequirement() {
document.forms("death")("GuardianName").setAttribute("required", "");
document.forms("death")("GuardianNumber").setAttribute("required", "");
//alert("Step4");
}
function validateForm() {
var a = document.forms("death")("GuardianName").value;
var b = document.forms("death")("GuardianNumber").value;
var c = document.forms("death")("FirstName").value;
var d = document.forms("death")("LastName").value;
if (document.getElementById("YesNo").selectedIndex == "1")
{
if (a == "" || b == "") {
alert("Please fill ALL required fields");
}
else {
alert("Registration Complete!");
}
}
else if (c == "" || d == "") {
alert("Please fill ALL required fields")
}
else {
alert("Registration Complete!")
}
}
</script>
</head>
<body>
<h2>Work Field Trip Registration!</h2>
<h4>Please enter your details.</h4>
<form name="death">
First Name:<br>
<input required type="text" name="FirstName"><br>
Last Name:<br>
<input required type="text" name="LastName"><br>
Gender:<br>
<select name="dMenu">
<option>Male</option>
<option>Female</option>
</select><br><br>
Are you under 18?
<select id="YesNo" onChange="HideReveal()" name="dMenu">
<option name="OptionNo" id="OptionNo" value="0">No</option>
<option name="OptionYes" id="OptionYes" value="1">Yes</option>
</select><br><br>
<div id="ifYes" style="display:none">
Please enter your Parent/Guardian's name:<br>
<input type="text" id="GuardName" name="GuardianName"><br>
Please enter your Parent/Guardian's phone number:<br>
<input type="text" id="GuardPhone" name="GuardianNumber"><br>
</div>
<input onClick="validateForm()" type="submit" value="Submit">
</form>
</body>
</html>
1) you don't need to call validate if you already set field to required. The browser will handle that for you.
2. I wonder why you used 'getElementbyId' in NoRequirement() but document.forms in AddRequirement().
In anycase here is a modified version of your code. cheers
<html>
<head>
<meta charset="utf-8">
<title>Work Field Trip Registration</title>
<script type="text/javascript">
function HideReveal() {
if (document.getElementById("YesNo").selectedIndex == "1") {
document.getElementById("ifYes").style.display = "block";
Required();
//alert('1st Option Tested');
}
else if (document.getElementById("YesNo").selectedIndex == "0") {
document.getElementById("ifYes").style.display = "none";
Required();
//alert('2nd Option Tested');
}
}
function Required() {
if (document.getElementById("YesNo").selectedIndex == "1") {
AddRequirement();
//alert("Step1");
}
else {
NoRequirement();
//alert("Step2");
}
}
function NoRequirement() {
document.getElementById("GuardName").removeAttribute("required");
document.getElementById("GuardPhone").removeAttribute("required");
//alert("Step3");
}
function AddRequirement() {
document.getElementById('GuardName').setAttribute("required","")
document.getElementById('GuardPhone').setAttribute("required","")
//alert("Step4");
}
</script>
</head>
<body>
<h2>Work Field Trip Registration!</h2>
<h4>Please enter your details.</h4>
<form name="death">
First Name:<br>
<input required type="text" name="FirstName"><br>
Last Name:<br>
<input required type="text" name="LastName"><br>
Gender:<br>
<select name="dMenu">
<option>Male</option>
<option>Female</option>
</select><br><br>
Are you under 18?
<select id="YesNo" onChange="HideReveal()" name="dMenu">
<option name="OptionNo" id="OptionNo" value="0">No</option>
<option name="OptionYes" id="OptionYes" value="1">Yes</option>
</select><br><br>
<div id="ifYes" style="display:none">
Please enter your Parent/Guardian's name:<br>
<input type="text" id="GuardName" name="GuardianName"><br>
Please enter your Parent/Guardian's phone number:<br>
<input type="text" id="GuardPhone" name="GuardianNumber"><br>
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>
Hi so i was reading how to validate html forms, all my validators client side are working woth patterns and type. The problem is when i press submit the javascript validation dont run. There is my code:
<script language="javascript">
function validateForm()
{
var xa = document.forms["regform"]["password"].value;
var xb = document.forms["regform"]["password2"].value;
var xc = document.forms["regform"]["email"].value;
var xd = document.forms["regform"]["email2"].value;
if (xa == xb && xc == xd){
return true; }
else{ return false; alert("Please enter a valid captcha code");}
}
$(document).ready(function(e) {
try {
$("body select").msDropDown();
} catch(e) {
alert(e.message);
}
});
</script>
Them the form:
<form name="regform" onsubmit="return validateForm();" action="actions/register_acc.php" method="post">
<input type="password" name="password" class="input-style" required="required">
<input type="password2" name="password" class="input-style" required="required">
<input name="email" class="input-style" placeholder="your#email.com" required="required" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
<input name="email2" class="input-style" placeholder="your#email.com" required="required" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
<input type="submit" value="ok">
</form>
Inside the form i also have these:
<select name="selectname" id="webmenu">
<option value="1">1</option>
<option value="2">2</option>
</select>
And in the head these:
<script src="js/msdropdown/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/msdropdown/jquery.dd.min.js" type="text/javascript"></script>
The problem lies in the validateForm method itself, specifically in the else block. You're returning false before the alert call. Swap the two calls around and you should see the alert message appear.
For clarity's sake, I would change the message in the alert box as it isn't directly relevant to the fields you're validating.
function validateForm()
{
var xa = document.forms["regform"]["password"].value;
var xb = document.forms["regform"]["password2"].value;
var xc = document.forms["regform"]["email"].value;
var xd = document.forms["regform"]["email2"].value;
if (xa == xb && xc == xd){
return true;
}
else {
alert("Please enter a valid captcha code");
return false;
}
}
See this Fiddle
Can you please take a look at This Demo and let me know why this bug is happening during the validation of two type of input selections?
Technically, what is happening is if user not select either of checkboxes and Select options and push the submit button the error message shows up and the validRequest boolean stays in false. Now if user ONLY select the checkboxes the situation is same the validRequest boolean is false and error message shows up BUT if user forgets to select the checkboxes and only selects from the list the validateQuery() validates the validRequest as True and then now error message and alert message pops up!
Can you please let me know why this is happening?
$(function () {
var validRequest = false;
function validateQuery() {
var selectedDoll = $('input:checkbox[name=doll]');
if ($(selectedDoll).is(':checked')) {
validRequest = true;
$('#err').html('');
} else {
validRequest = false;
$('#err').html('Some Thing Wrong!');
}
var selectedIcecream = $("#icecream").val();
if (selectedIcecream == 0) {
validRequest = false;
$('#err').html('Some Thing Wrong!');
} else {
validRequest = true;
$('#err').html('');
}
}
$("#isValid").on("click", function () {
validateQuery();
if(validRequest){ alert('Ready To Go');}
console.log(validRequest);
});
});
#err{color:red;}
<div>
<input type="checkbox" name="doll" value="cat" />Cats
<br />
<input type="checkbox" name="doll" value="dog" />Dogs
<br />
<input type="checkbox" name="doll" value="bird" />Birds
<br />
<br />
<select id="icecream">
<option value="0">Select From List</option>
<option value="chocolate">Chocolate</option>
<option value="vanilla">Vanilla</option>
<option value="strawberry">Strawberry</option>
<option value="caramel">Caramel</option>
</select>
</div>
<p>
<input type="submit" id="isValid" value="Submit now" />
</p>
<p>
<div id="err"></div>
</p>
Fixed: http://jsfiddle.net/byk309j8/7/
The problem was that you had 2 independent if statements while you must have only one. Also you were checking if the select box is empty == 0 instead of not empty !== 0
$(function () {
var validRequest = false;
function validateQuery() {
var selectedDoll = $('input:checkbox[name=doll]');
var selectedIcecream = $("#icecream").val();
// checkbox is not checked, but select is
if ($(selectedDoll).is(':checked') && selectedIcecream == 0) {
validRequest = false;
$('#err').html('select not selected');
} else if ($(selectedDoll).is(':checked') == false && selectedIcecream != 0) {
validRequest = false;
$('#err').html('checkbox not checked');
} else if ($(selectedDoll).is(':checked') == false || selectedIcecream == 0) {
validRequest = false;
$('#err').html('checkbox not checked or select not selected');
} else {
validRequest = true;
$('#err').html('');
}
}
$("#isValid").on("click", function () {
validateQuery();
if(validRequest){ alert('Ready To Go');}
console.log(validRequest);
});
});
<div>
<input type="checkbox" name="doll" value="cat" />Cats
<br />
<input type="checkbox" name="doll" value="dog" />Dogs
<br />
<input type="checkbox" name="doll" value="bird" />Birds
<br />
<br />
<select id="icecream">
<option value="0">Select From List</option>
<option value="chocolate">Chocolate</option>
<option value="vanilla">Vanilla</option>
<option value="strawberry">Strawberry</option>
<option value="caramel">Caramel</option>
</select>
</div>
<p>
<input type="submit" id="isValid" value="Submit now" />
</p>
<p>
<div id="err"></div>
</p>
#err{color:red;}
I am trying to add a Span after my Input that will have the class "error" and the text "test".
I've tried the append, and insertAfter methods. I can get the code to work on jsfiddle but I cannot get the code to work on my application.
I have put the HTML and JS/Jquery below. My end result would have a Span (with the class error) next to each input with the type text. I would then set a value for this span based on a validation loop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Zito - Lab 7</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="reservation.js" type="text/javascript"></script>
</head>
<body>
<h1>Reservation Request</h1>
<form action="response.html" method="get"
name="reservation_form" id="reservation_form">
<fieldset>
<legend>General Information</legend>
<label for="arrival_date">Arrival date:</label>
<input type="text" name="arrival_date" id="arrival_date" autofocus><br>
<label for="nights">Nights:</label>
<input type="text" name="nights" id="nights"><br>
<label>Adults:</label>
<select name="adults" id="adults">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<label>Children:</label>
<select name="children" id="children">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
</fieldset>
<fieldset>
<legend>Preferences</legend>
<label>Room type:</label>
<input type="radio" name="room" id="standard" class="left" checked>Standard
<input type="radio" name="room" id="business" class="left">Business
<input type="radio" name="room" id="suite" class="left last">Suite<br>
<label>Bed type:</label>
<input type="radio" name="bed" id="king" class="left" checked>King
<input type="radio" name="bed" id="double" class="left last">Double Double<br>
<input type="checkbox" name="smoking" id="smoking">Smoking<br>
</fieldset>
<fieldset>
<legend>Contact Information</legend>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email"><br>
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
</fieldset>
<input type="submit" id="submit" value="Submit Request"><br>
</form>
</body>
</html>
JS/JQuery
$(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
var phonePattern = /\b(\d{3})([-])(\d{3})([-])(\d{4})\b/;
var datePattern = /\b(0[1-9]|1[012])([/])(0[1-9]|1[0-9]|2[0-9]|3[01])([/])((20)\d\d)\b/;
$(":text").after("<span class='error'>*</span>");
$("#arrival_date").focus();
$("#reservation_form").submit(
function(event) {
var isValid = true;
// validate arrival date
var arrivalDate = $("#arrival_date").val();
if (arrivalDate == "") {
$("#arrival_date").next().text("This field is required");
isValid = false;
} else if (!datePattern.test(arrivalDate)) {
$("#arrival_date").next().text("Must be in the format 12/12/2012");
isValid = false;
} else {
$("#arrival_date").next().text("");
}
// validate nights
var nights = $("#nights").val();
if (nights == "") {
$("#nights").next().text("This field is required");
isValid = false;
} else if ((isNaN(parseInt(nights))) || (parseInt(nights) <=0)) {
$("#nights").next().text("This field must be a number and not zero");
isValid = false;
} else {
$("#nights").next().text("");
}
// validate name
var name = $("#name").val();
if (name == "") {
$("#name").next().text("This field is required");
isValid = false;
} else {
$("#name").next().text("");
}
// validate email
var email = $("#email").val();
if (email == "") {
$("#email").next().text("This field is required");
isValid = false;
} else if (!emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
// validate phone
var phone = $("#phone").val();
if (phone == "") {
$("#phone").next().text("This field is required");
isValid = false;
} else if (!phonePattern.test(phone) ) {
$("#phone").next().text("Must be in the format 999-999-9999");
isValid = false;
} else {
$("#phone").next().text("");
}
if (isValid == false) {
event.preventDefault();
$("#arrival_date").focus();
}
}
);
}); // end ready
Most easy way is to add a Div container around the form and just append the warning to that. To effectively append after an element you need to give it a class or id.
var email = $("#email"); //using class instead of input:text
var html = "<span class='error'>TEST!</span>"
email.after( html );
But I personally would like something like this better:
var generateError = function(){
var html = "<div id='error' style='top: 0; left:0; width:100%; height: 50px; background-color: red; text-allign: center; display:none; z-index: 100;'> ERROR!!</div>"
$(body).append( html );
}
var showError = function( text ){
var err = $("#error");
err.html( text );
err.show(500).delay(2000).hide(500);
}
Code is fairly self-explaining, but this will make two functions: generateError and showError.
generateError you need to call before you want to show the error, possibly when the page loads it will add a small header on top of all you other elements and will appear hidden.
showError uses a text argument with the error you want to show. Then it will set the text to the div and show it for two seconds.
This then is more what you are looking for?
$(document).ready(function () {
var input = $("input");
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
input.keypress(function (ele) {
// if regex.test( input ) === false
createErrors(ele.target);
})
});
var createErrors = function (ele) {
$('<span>TEST!</span>').insertAfter(ele);
$("#arrival_date").focus();
};
This works on keypress, that means the regex gets checked every time a key is pressed. It also passes the element where the user is typing as parameter, this means that you wont get errors for all input:text, but only for the ones where there is an error.
Updated Fiddle (still not perfect, but if its an school exercise this will help you to finish it :)
After my form is submitted, I'd like to reset my form to display the original blank values. Here's the code:
PHP Form
<form action="index.php" method="post" id="contact_form" >
<div id="topic_error" class="error"><img src="images/error.png" /> What category should this be filed in?</div>
<div>
<select name="topic" id="topic">
<option value="">Please select a topic...</option>
<option value=" Computer Repair ">Computer Repair</option>
<option value=" Website Design ">Website Design</option>
<option value=" Say Hi ">Just Want to Say Hi</option>
</select>
</div>
<h4>NAME:</h4><div id="name_error" class="error"><img src="iamges/error.png" /> Please enter your name</div>
<div><input class="contact_name" type="text" name="name" id="name" placeholder="Enter Name" /></div>
<H4>EMAIL:</H4><div id="email_error" class="error"><img src="images/error.png" /> Please enter your email</div>
<div><input class="contact_email" type="text" name="email" id="email" placeholder="you#mail.com" /></div>
<h4>SUBJECT:</h4><div id="subject_error" class="error"><img src="images/error.png" /> Please enter a subject</div>
<div><input class="contact_subject" type="text" name="subject" id="subject" placeholder="How did you become so awesome?" /></div>
<h4>MESSAGE:</h4><div id="message_error" class="error"><img src="images/error.png" /> Please give us a few more details</div>
<div><textarea class="contact_message" name="message" id="message" placeholder="Give us some details"></textarea></div>
<div id="mail_success" class="success"><img src="images/success.png" /> Thank you. The mailman is on his way.</div>
<div id="mail_fail" class="error"><img src="images/error.png" /> Sorry, we don't know what happened. Please try again later.</div>
<div id="cf_submit_p">
<input class="submit" type="submit" id="send_message" value="">
</div>
</form>
The contact.js file
$(document).ready(function(){
$('#send_message').click(function(e){
e.preventDefault();
var error = false;
var topic = $('#topic').val();
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
if(topic.length == 0){
var error = true;
$('#topic_error').fadeIn(500);
} else {
$('#topic_error').fadeOut(500);
}
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
} else {
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
} else {
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
} else {
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
} else {
$('#message_error').fadeOut(500);
} if(error == false){
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
$.post("send_email.php", $("#contact_form").serialize(),function(result){
if(result == 'sent'){
$('#cf_submit_p').remove();
$('#mail_success').fadeIn(500);
} else {
$('#mail_fail').fadeIn(500);
$('#send_message').removeAttr('disabled').attr('value', 'Send Message');
}
});
}
});
});
I don't think the send_email.php file is needed, but I can put that up here if need be. I would assume (I know what happens when you assume) that this can be done with some sort of trigger in the javascript. I did try to add the line form.trigger('reset'); after the $('#mail_success').fadeIn(500); line but that did not work
It would be $("#contact_form").trigger("reset"), and $("#contact_form")[0].reset() should also work.
$('#contact_form').trigger('reset') should work.