When I click the submit button in my signup form the JavaScript function is not invoked but when I try a online editor its working fine but not in my Pycharm IDE with firefox browser. When I submit the form it submits when I have an input field unfilled which can be found by my JavaScript function 'emp_details' but its not happening.
My signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Employee Details</title>
<script type="text/javascript">
function emp_details(){
var id = document.forms["form2"]['id'].value;
var fname = document.forms["form2"]["fname"].value;
var lname = document.forms["form2"]["lname"].value;
var Password = document.forms["form2"]['password'].value;
var designation = document.forms["form2"]['designation'].value;
var experience = document.forms["form2"]['experience'].value;
window.alert("fname");
var alphaExp = /^[a-zA-Z]+$/;
var pass = /^[a-zA-Z0-9#$#]{8,15}$/;
if(!id ||!fname || !lname ||!Password ||!designation ||!experience)
{
alert("Please enter all the fields");
return false;
}
else
{
if(!isNaN(id))
{
if(fname.match(alphaExp))
{
if(lname.match(alphaExp))
{
if(Password.match(pass))
{
/*var values = Sijax.getFormValues("#form2");
alert(values);
Sijax.request('submit',[values]);*/
return true;
}
else
{alert("Enter a valid password ");
return false;
}
}
else
{
alert("Enter a valid last name");
return false;
}
}
else
{
alert("Enter a valid first name");
return false;
}
}
else
{
alert("ID must be in Numbers");
return false;
}
}
}
</script>
<style>
label {
display: inline-block;
width: 140px;
text-align: right;
}
label,input,select{
margin-left:40px;
}
</style>
</head>
<body style="font-family: Liberation Sans">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to my site</h2><br>
</div>
<div style="margin-left:15%" >
<form name="form2" id="form2" method="post" action = "http://127.0.0.1:2908/signup" >
<br><br><br>
<label id = "id">ID</label> <input type="text" name = "id" placeholder = "ID" style = "padding-left: 0.2%;"><br><br>
<label id = "fname">First Name</label> <input type="text" name = "fname" placeholder = "First Name" style = "padding-left: 0.2%;"><br><br>
<label id = "lname">Last Name</label> <input type="text" name = "lname" placeholder = "Last Name" style = "padding-left: 0.2%;"><br><br>
<label id = "password">Password</label>
<input type="password" name = "password" placeholder = "Password" style = "padding-left: 0.2%;"><br><br>
<label id = "department">Department</label>
<select name="department">
<option value="Ecategory"> Category </option>
<option value="Developer Team"> Developer Team</option>
<option value="Testing Team"> Testing Team</option>
<option value="Network Team"> Network Team</option>
<option value="Server Maintance Team"> Server Maintance Team</option>
</select><br><br>
<label id = "designation">Designation</label>
<input type="text" name = "designation" placeholder = "Designation" style = "padding-left: 0.2%;"><br><br>
<label id = "experience">Experience</label>
<input type="text" name = "experience" placeholder = "Experience" style = "padding-left: 0.2%;"><br><br>
<label id = "emp_type">Admin</label>
<input type="radio" id = "r1" value="Yes" name="emp_type" ><span>Yes</span>
<input type="radio" id = " r2" value="No" name="emp_type"checked="checked"><span>No</span>
<br><br><br>
<input type="submit" value="Submit" onsubmit="return emp_details()" style="font-size:15pt;color:white;background-color: #3f51b5;border:2px solid ;padding:7px;padding-left:100px;padding-right:100px">
</form></div>
</body>
</html>
The onsubmit attribute should be on the form tag, not on your submit button. Quoted from MDN:
The submit event is fired when a form is submitted.
Note that submit is fired only on the form element, not the button or submit input. (Forms are submitted, not buttons.)
<form name="form2" id="form2" method="post" action="http://127.0.0.1:2908/signup"
onsubmit="return emp_details()">
<!--- .... --->
<input type="submit" value="Submit">
</form>
Related
Im partly there but it would be helpful if any of you guys could send the entire code .
1) Create a form with the below given fields and validate the same using javascript or jquery.
Name : Text box- mandatory
Gender : Radio Button
Age : Text box - Accept Number only - (check for valid Age criteria)
Email : Text box - should be in format example#gmail.com
Website : Text box - should be in format http://www.example.com
Country : Select box with 10 countries
Mobile : Text box - should be a 10 digit number - Display this field only after the user selects a country
Social Media Accounts : Facebook, Google, Twitter (3 checkboxes) - Display Social media section only if selected Country is India
I agree the Terms and Conditions - Checkbox
All fields are mandatory and show error messages for all fields(if not valid)
Only allow to submit form after checking the 'I agree' checkbox.
<!DOCTYPE html>
<html>
<head>
<title>Get Values Of Form Elements Using jQuery</title>
<!-- Include CSS File Here -->
<link rel="stylesheet" href="form_value.css"/>
<!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="form_value.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#social").hide() ;
// $("#hide").click(function(){
// $("social").hide();
// });
// var country = document.getElementByName("country")[0].value;
// if (country.value == "India") {
// $("#show").click(function(){
// $("social").show();
// });
// }
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.email_id.value)) {
alert("You have entered an invalid email address!")
return (false)
}
});
</script>
</head>
<body onload="disableSubmit()">
<div class="container">
<div class="main">
<h2>Get Values Of Form Elements Using jQuery</h2>
<form action="">
<!-- Text -->
<br>
<br>
<label>Name :</label>
<input type="text" id="text" name="name" value=""required/><br>
<!-- Radio Button -->
<br><br><br>
<label>Gender:</label>
<input type="radio" name="male" value="Male">Male
<input type="radio" name="female" value="Female">Female
<br><br>
<!-- Textarea -->
<label>Email :</label>
<input type="text" id="Email" value="" id="Email"/>
<br>
<br><br>
Age: <input type="text" id="Age" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
<br><br>
<label> Website:</label>
<input type="text" id="text" value="" name = "Website" id="website" />
<script type="text/javascript">
function validate() {
if(Website.value.length==0)
{
document.getElementById("Website").innerHTML="Should be in the format http://www.example.com ";
}
}
</script>
<br><br>
<label>Country:</label>
<select class="country" id = "country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
<option value="uae">United Arab Emirates</option>
<option value="germany">Germany</option>
<option value="france">France</option>
<option value="netherlands">Netherlands</option>
<option value="yemen">Yemen</option>
<option value="pakistan">Pakistan</option>
<option value="russia">Russia</option>
</select>
<br><br>
<label>Mobile:</label>
<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">
<script type="text/javascript">
function phoneno(){
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
}
</script>
<br><br>
<div id = "social" >
<p>Social Media Accounts.</p> <input type="checkbox" id="Facebook" value="Facebook"><label for="Facebook"> Facebook</label><br> <input type="checkbox" id="Google" value="Google"><label for="Google"> CSS</label><br> <input type="checkbox" id="Twitter" value="Twitter"><label for="Twitter"> Twitter</label><br>
</div>
<br>
<br>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)"> I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</script>
</form>
</div>
</body>
</html>
this is my js page content form_value.js
$(document).ready(function() {
// Function to get input value.
$('#text_value').click(function() {
var text_value = $("#text").val();
if(text_value=='') {
alert("Enter Some Text In Input Field");
}else{
alert(text_value);
}
});
// Funtion to get checked radio's value.
$('#gender_value').click(function() {
$('#result').empty();
var value = $("form input[type='gender']:checked").val();
if($("form input[type='gender']").is(':checked')) {
$('#result').append("Checked Radio Button Value is :<span> "+ value +" </span>");
}else{
alert(" Please Select any Option ");
}
});
// Get value Onchange radio function.
$('input:gender').change(function(){
var value = $("form input[type='gender']:checked").val();
alert("Value of Changed Radio is : " +value);
});
// Funtion to reset or clear selection.
$('#radio_reset').click(function() {
$('#result').empty();
$("input:radio").attr("checked", false);
});
$('#Email').click(function() {
function validate(Email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za- z]{2,4})$/;
//var address = document.getElementById[email].value;
if (reg.test(email) == false)
{
alert('Should be in the format example#gmail.com');
return (false);
}
}
});
});
$("#Age").click(function() {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
function handleChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 100) input.value = 100;
}
});
</script>
<!DOCTYPE html> <html> <head> <script> function validateForm() {
var name = document.forms["myForm"]["fname"].value;
var gender = document.forms["myForm"]["gender"].value;
var age = document.forms["myForm"]["age"].value;
var a = parseInt(age);
var email = document.forms["myForm"]["email"].value;
var url = document.forms["myForm"]["website"].value;
var country = document.forms["myForm"]["country"].value;
var mobileCountry = document.forms["myForm"]["mobileCountry"].value;
var mcLength = mobileCountry.length;
if (name == "") {
alert("Name Field is mandatory");
return false;
}
if (gender != "male" && gender != "female") {
alert("Atleast one Gender has to be chosen");
return false;
}
if(isNaN(a)){
alert("Age is compulsory and must be a number");
return false;
}
if(email == ""){
alert("Email address is required");
}
else if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
} else{
alert("Email address entered is invalid");
return false;
}
if(/^(ftp|http|https):\/\/[^ "]+$/.test(url)){
} else{
alert("Website url entered is invalid");
return false;
}
if(country != "choose"){
document.getElementById("mc").style.display = "block";
} else{
document.getElementById("mc").style.display = "none";
}
if(mcLength != 10){
alert("Number must be ten digits");
return false;
}
} function displaySocial(){ var social =
document.getElementById("social");
var mc = document.getElementById("mobileCountry");
var country = document.getElementById("country");
var selectedValue = country.options[country.selectedIndex].value;
if (selectedValue != "choose") {
if(selectedValue == "india"){
if(social.style.display = "none"){
social.style.display = "block";
} else{
social.style.display = "none";
} } else{
social.style.display = "none"; }
if(mc.style.display = "none"){
mc.style.display = "block";
} else{
mc.style.display = "none"; } } else{
mc.style.display = "none"; }
} </script> </head> <body> <form name="myForm" action="/action_page_post.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"><br> Gender: <input type="radio" name="gender" value="male"> Male <input type="radio" value="female" name="gender"> Female <br> age: <input type="text" name="age"><br> email: <input type="text" name="email"><br> website: <input type="text" name="website"><br> country: <select type="text" name="country" id="country" onclick="displaySocial()"><option value="choose">--choose--</option><option value="usa">USA</option><option value="uk">UK</option><option value="ng">Nigeria</option><option value="india">India</option></select><br> <span id="mobileCountry" style="display: none;">mobile country: <input type="text" name="mobileCountry"><br></span> <span id="social" style="display: none;">Social Media: <input type="radio" name="gender"> Facebook <input type="radio" name="gender"> Google <input type="radio" name="gender"> Twitter</span> <br> <p> <input type="submit" value="Submit"> </form> <p id="error"></p> </body> </html>
I have a html form with such structure:
...
<select name="Employee">
<option>a</option>
<option>b</option>
</select>
<input type="checkbox" name="email" value="Yes" unchecked>Include Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show()" id="refresh">
...
And a div:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:</div>
<div class="ft_tbl_data"></div>
</div>
How can I show my values in div section by pressing the button without reloading the entire page?
I know Javascript a bit, but unfortunately, didn't find the answer yet.
Thank you in advance!
Here is one solution, using unobtrusive vanilla javascript.
The function showData() runs when the button is clicked.
Then, the function showData():
gets the Boolean value of each checkbox (either true if checked or false if unchecked)
rewrites the Boolean value as a string (a value of true becomes 'Yes' and a value of false becomes 'No')
rewrites the relevant data field, including the string.
function showData() {
var emailValue = document.querySelector('input[value="email"]').checked;
var phoneValue = document.querySelector('input[value="phone"]').checked;
var data = document.getElementsByClassName('data')[0];
var dataFields = data.getElementsByTagName('div');
if (emailValue === true) {emailValue = 'Yes';} else {emailValue = 'No';}
if (phoneValue === true) {phoneValue = 'Yes';} else {phoneValue = 'No';}
for (var i = 0; i < dataFields.length; i++) {
switch (i) {
case (0) : dataFields[i].textContent = 'E-Mail: ' + emailValue; break;
case (1) : dataFields[i].textContent = 'Phone: ' + phoneValue; break;
}
}
}
var button = document.querySelector('input[type="button"]');
button.addEventListener('click',showData,false);
form, .data, label, input[type="button"] {
display: block;
}
form, .data {
float: left;
width: 200px;
}
input[type="button"] {
margin-top: 24px;
}
<form>
<label><input type="checkbox" name="contact" value="email" unchecked>Include Email Contact</label>
<label><input type="checkbox" name="contact" value="phone" unchecked>Include Phone Contact</label>
<input type="Button" value="Generate">
</form>
<div class="data">
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_meta">Phone:</div>
</div>
set some IDs for your divs you wish to take/assign values from/to and put this code
IncludeEmailCheckBox is for your "include Email" checkbox
EmailToDiv is for your div to get the email
EmailFromDiv is for your input for Email
IncludePhoneCheckBox is for your "include Phone" checkbox
PhoneToDiv is for your div to get the Phone
PhoneFromDiv is for your input for Phone
function show(){
if (document.getElementById("IncludeEmailCheckBox").checked){
document.getElementById("EmailToDiv").innerHTML = document.getElementById("EmailFromDiv").innerHTML ;}
if (document.getElementById("IncludePhoneCheckBox").checked){
document.getElementById("PhoneToDiv").innerHTML = document.getElementById("PhoneFromDiv").innerHTML ;}
return false;
}
Remember to change IDs as nessesary
Get elements of class by calling document.getElementsByClassName(class_name)
Example javascript code below
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var x = document.getElementsByClassName("ft_name");
x[0].innerHTML = form.name.value;
x = document.getElementsByClassName("ft_tbl_meta");
x[0].innerHTML = form.email.value; // name email is one provided in form
// Do same for all other classes
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
<input type="checkbox" name="email" value="Yes" unchecked>Include
Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show(this.form)" id="refresh">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
here is your view (I updated) using Jquery:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:<span id="email_here"></span></div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:<span id="phone_here"></span></div>
<div class="ft_tbl_data"></div>
</div>
Now fetching and printing values:
var Employee = $( "select[name=Employee]" ).val();
$('.ft_name').html(Employee);
var email = $( "input[name=email]" ).val();
$('#email_here').html(email);
var phone = $( "input[name=phone]" ).val();
$('#phone_here').html(phone);
var jobTitle = $( "input[name=jobTitle]" ).val();
$('.ft_pos').html(jobTitle);
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 :)
I've created a form, that I need to validate with JavaScript or using Jquery. How would I validate if the dropdown list has the value "Title" and if the text box is empty and display it on the page rather then an alert box :
<form action="" method="post" accept-charset="UTF-8" name="myForm">
<option value="Title" id="title_3-0" disabled selected>Title</option><option value="Mr" id="title_3-1">Mr</option>
<option value="Mrs" id="title_3-2">Mrs</option><option value="Miss" id="title_3- 3">Miss</option>
<option value="Ms" id="title_3-4">Ms</option><option value="Dr" id="title_3-5">Dr</option>
<option value="Professor" id="title_3-6">Professor</option></select></div></div>
TextBox:
<input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
I also have a button.
Here is a start:
<script>
function validateForm()
{
var return_value = true;
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("error").innerHTML += "First name must be filled out<br />";
return_value = false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("error").innerHTML += "You need to select a title<br />";
return_value = false;
}
return return_value;
}
</script>
<span id="error"></span>
<form name="myForm" onsubmit="return validateForm()" method="post">
First name: <input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
<input type="submit" value="Submit">
</form>
If you like, you can also put an "error span element" above/beneath each field and set each error individually:
<script>
function validateForm()
{
var return_value = true;
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("error1").innerHTML = "First name must be filled out";
return_value = false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("error2").innerHTML = "You need to select a title";
return_value = false;
}
return return_value;
}
</script>
<form name="myForm" onsubmit="return validateForm()" method="post">
First name: <input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
<span id="error1"></span>
Title: <input .... >
<span id="error2"></span>
<input type="submit" value="Submit">
</form>
Since you are new to this, look up these links and read up. It will guide you through it. That's better than us giving you all the code. Because this kind of form validation is important and hence you better learn it from scratch.
Link-1
Link-2
Link-3 (using library)
Html:
<select id="ddl"> <option value="Title" id="title_3-0" selected>Title</option><option value="Mr" id="title_3-1">Mr</option>
<option value="Mrs" id="title_3-2">Mrs</option><option value="Miss" id="title_3- 3">Miss</option>
<option value="Ms" id="title_3-4">Ms</option><option value="Dr" id="title_3-5">Dr</option>
<option value="Professor" id="title_3-6">Professor</option></select>
<input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
<input type="button" value="Submit" id="btn"/>
<span id="error"/>
JQuery:
$('#btn').click(function (){
if(($('#amf-input-firstname_4').val()=='') || ($("#ddl :selected").val() == 'Title'))
{
$('#error').html('Please select title and enter name.');
}
else
{
$('#error').html('Success');
}
return false;
});
Demo:
http://jsfiddle.net/8h8HF/
So I made a simple javascript form validator which creates a box with the error message using DOM. But I can't figure out a way how to reset all these changes when i reset the form using
<button type="reset">
I would like to know how it's done please.
Thanks.
The Code
<html>
<head>
<script type="text/javascript">
function validate(){
var fname = document.getElementById("fname");
var surname = document.getElementById("surname");
if(fname.value === "" || fname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("fname").style.display = "block";
return false;
}
//Verify Last Name
if(surname.value === "" || surname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("surname").style.display = "block";
return false;
}
}//End Validate Function
</script>
<style type="text/css">
#sbody{
width: 100px;
height: 100px;
background-color: #f3f3f3;
display:none;
}
.vis{
display: none;
font-size: 12px;
}
</style>
</head>
<body>
<section id="sbody">
<span id="fner" class="vis">First Name is missing.</span>
<span id="lner" class="vis">Surame is missing.</span>
</section>
<form id="registerForm" method="POST" action="register.php" onsubmit="return validate()">
<label for="fname" class="labelStyle">First Name: </label>
<input id="fname" name="fname" type="text" value="">
<label for="surname" class="labelStyle">Surname: </label>
<input id="surname" name="surname" type="text" value="">
<button type="submit">Sign Up</button>
<button type="reset">Reset</button>
</form>
</body>
</html>
The browser cannot magically figure out what has to be done to reset the custom changes.
However you can listen to the reset event of the form using element.addEventListener.
DEMO
HTML
<form id="test">
<div id="errors-ct">The form has errors</div>
<button type="reset">Reset</button>
</form>
JS
//wait for the DOM to be ready
document.addEventListener('DOMContentLoaded', function () {
//store a reference to the errors container div
var errorsCt = document.getElementById('errors-ct');
//listen to the reset event of the form
document.getElementById('test').addEventListener('reset', function (e) {
var form = e.target; //this is how you could access the form
//hide the errors container
errorsCt.style.display = 'none';
});
});
If you want to reset the form, as if user hadn't made any selections or added any input, then just set all form element values to their default value, or empty.
jsFiddle
<div>
<form action="/echo/html" method="get">
<input type="text" placeholder="username" />
<br/>
<input type="password" placeholder="password" />
<br/>
<input type="checkbox" value="test" data-default="checked" checked="checked"/>
<br/>
<button type="reset" value="reset" onclick="resetForm()">reset</button>
<br/>
</form>
<div id="err">Some error message</div>
</div>
window.resetForm = function () {
var fields = $('input'),
uname, pass, check;
uname = $(fields.get(0));
pass = $(fields.get(1));
check = $(fields.get(2));
$("#err").text("");
uname.val('');
pass.val('');
if (check.attr("data-default") == "checked") {
check.attr("checked", "checked");
} else {
check.removeAttr("checked");
}
}