I am using AMP to develop my website. In that, I am using amp-script. When I use document.getElementById, it is giving the element data differently. I am looking for some properties like value etc. in it. But, can't those. See the below screenshot to look at the contents.
Please help me solve this.
Thank you...
EDIT: Added code snippet
HTML:
<form action="click" target="_blank" name="contact_form" id="contact_form" class="contact-form__block">
<div class="form__group">
<label for="message" class="form__label message_label">The idea that is brewing in your mind?
*</label>
<textarea name="message" id="form__textarea" class="form__textarea"></textarea>
</div>
<div class="form__group">
<label for="name" class="form__label name_label">Name </label>
<input type="text" name="name" id="form__name" class="form__input name" value="" autocomplete="off">
</div>
<div class="form__groups">
<div class="form__group">
<label for="phone" class="form__label phone_label">Phone Number </label>
<input type="text" name="phone" id="form__phone" class="form__input phone" value=""
autocomplete="off">
<!-- error message start -->
<!-- <div class="form__error e_mail">Please enter all required details.</div> -->
<!-- error message end -->
</div>
<div class="form__group">
<label for="mail" class="form__label email_label">Email *</label>
<input type="text" name="mail" id="form__mail" class="form__input mail">
</div>
</div>
<div class="form__group">
<div class="form-button__block">
<button type="button" name="submit" class="form__submit" id="form-submit">
<div class="arrow__btn-link-text">Let's Connect</div>
<amp-img src="stroke-arrow-right.svg" height="1" width="1"
alt="arrow right icon" class="arrow__btn-icon">
</button>
<!-- <div class="button--border"></div> -->
</div>
<div class="error_box">
<span class="error_message"></span>
</div>
</div>
</form>
JS:
var form = document.getElementById("form-submit"), msg;
form.addEventListener("click", function(event) {
event.preventDefault();
if (document.getElementById('form__textarea').value == '') {
msg = false;
} else {
msg = true;
}
if (document.getElementById('form__mail').value == '') {
email = false;
} else {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var validEmail = emailReg.test(document.getElementById('form__mail').value);
if (!validEmail) {
email = false;
} else {
email = true;
}
}
if (document.getElementById('form__phone').value == '') {
phone = true;
document.getElementById('form__phone').value = "";
} else {
var phoneReg = /^([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/;
var validPhone = phoneReg.test(document.getElementById('form__phone').value);
if (!validPhone) {
phone = false;
} else {
phone = true;
}
}
if (document.getElementById('form__name').value == '') {
document.getElementById('form__name').value = "";
} else {
name = true;
}
if (!msg || !email || !phone) {
console.log("Error in formmmmmmmmmmmmm");
return false;
} else {
console.log("valid formmmmmmmmmmmmmmmmmmmmmm");
}
});
Related
I have this js styling but it seems to not work. I don't know what is wrong
<div id="SignUp-Password">
<div id="SignUp-LG-Password">Password:</div>
<input
size="42"
type="Password"
maxlength="42"
name="SignUp-Input-Password"
id="SignUp-Input-Password">
<input id="SignUp-CheckBox-Password"
type="checkbox"
name="SignUp-CheckBox-Password">
<div id="SignUp-Password-Show">Show</div>
<span id="SignUp-Password-Match/Notmatch"/>
</div>
<div id="SignUp-Password-Repeat">
<div id="SignUp-LG-Password-Repeat">Password Repeat:</div>
<input
size="42"
type="text"
maxlength="42"
name="SignUp-Input-Password-Repeat"
id="SignUp-Input-Password-Repeat">
<div id="SignUp-Password-Strong"></div>
<div class="registrationFormAlert" id="divCheckPasswordMatch"></div>
</div>
java
function checkPasswordMatch() {
var password = $("#SignUp-Input-Password").val();
var confirmPassword = $("#SignUp-Input-Password-Repeat").val();
if (password != confirmPassword)
$("#divCheckPasswordMatch").html("Passwords do not match!").style.color = "red";
else
$("#divCheckPasswordMatch").html("Passwords match.").style.color = "green";
}
$(document).ready(function () {
$("#SignUp-Input-Password-Repeat").keyup(checkPasswordMatch);
});
I would think this is easy for you but I need some help with javascript.
you can also see this http://jsfiddle.net/fLqujmp3/
Your syntaxt to set style incorrect, change to
$("#divCheckPasswordMatch").css("color","red");
If you want to use javascript, change it to
document.getElementById("divCheckPasswordMatch").style.color = "red";
function checkPasswordMatch() {
var password = $("#SignUp-Input-Password").val();
var confirmPassword = $("#SignUp-Input-Password-Repeat").val();
if (password != confirmPassword){
$("#divCheckPasswordMatch").html("Passwords do not match!");
document.getElementById("divCheckPasswordMatch").style.color = "red";
//$("#divCheckPasswordMatch").css("color","red");
}
else{
$("#divCheckPasswordMatch").html("Passwords match.")
$("#divCheckPasswordMatch").css("color","green");
}
}
$(document).ready(function () {
$("#SignUp-Input-Password-Repeat").keyup(checkPasswordMatch);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="SignUp-Password">
<div id="SignUp-LG-Password">Password:</div>
<input
size="42"
type="Password"
maxlength="42"
name="SignUp-Input-Password"
id="SignUp-Input-Password">
<input id="SignUp-CheckBox-Password"
type="checkbox"
name="SignUp-CheckBox-Password">
<div id="SignUp-Password-Show">Show</div>
<span id="SignUp-Password-Match/Notmatch"/>
</div>
<div id="SignUp-Password-Repeat">
<div id="SignUp-LG-Password-Repeat">Password Repeat:</div>
<input
size="42"
type="text"
maxlength="42"
name="SignUp-Input-Password-Repeat"
id="SignUp-Input-Password-Repeat">
<div id="SignUp-Password-Strong"></div>
<div class="registrationFormAlert" id="divCheckPasswordMatch"></div>
</div>
I have created a form and a form validation script that checks if all fields are filled in, the name and city fields contain only letters, the age and phone fields contain only numbers and if the entered email is a valid one. When used in the console, all of the statements work, but when I fill in every field, or fill in invalid values in the email field or phone number and age field, I still get an error message saying that the name and city field must contain only letters.
I have tried writing out every statement alone and also checking them one by one.
HTML & JS
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="name" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="age" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="city" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="email" class="form-control" id="InputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<!-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> -->
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>
<script>
function validateForm() {
var name_cityRegex = /^[a-zA-Z]+$/;
var emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
var age_phoneRegex = /^\d+$/;
var nameValue = $('#inputName').val();
var cityValue = $('#inputCity').val();
var ageValue = $('#inputAge').val();
var phoneValue = $('#inputPhone').val();
var nameResult = name_cityRegex.test(nameValue);
var cityResult = name_cityRegex.test(cityValue);
var ageResult = age_phoneRegex.test(ageValue);
var phoneResult = age_phoneRegex.test(phoneValue);
var mailValue = $('#InputEmail1').val();
var mailResult = emailRegex.test(mailValue);
$(".btn.btn-primary.submit").click(function () {
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
else if (nameResult == false || cityResult == false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
})
});
</script>
When I leave all fields empty the warning is ok. But when I do anything else I only get the warning that I can only use letters in the fields Name and City.
All help is greatly appreciated for a beginner!
I think you are failing to reassign the variables outside of the onClick function. I have tested below code and it works for me, i admit it is probably not a perfect solution reassigning all the variables each time and perhaps you could place some in global scope such as the RegEx statements. I also removed the loop as i don't think you need to loop over everything 5 times to check.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="text" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="text" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="email" class="form-control" id="InputEmail" aria-describedby="emailHelp" placeholder="Enter email">
<!-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> -->
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>
<script>
$(".btn.btn-primary.submit").click(function () {
let name_cityRegex = /^[a-zA-Z]+$/;
let emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
let age_phoneRegex = /^\d+$/;
let nameValue = $('#inputName').val();
let cityValue = $('#inputCity').val();
let ageValue = $('#inputAge').val();
let phoneValue = $('#inputPhone').val();
let nameResult = name_cityRegex.test(nameValue);
let cityResult = name_cityRegex.test(cityValue);
let ageResult = age_phoneRegex.test(ageValue);
let phoneResult = age_phoneRegex.test(phoneValue);
let mailValue = $('#InputEmail').val();
let mailResult = emailRegex.test(mailValue);
if (nameValue == '' || cityValue == '' || ageValue == '' || phoneValue == '' || mailValue == '') {
$('.alert.alert-danger').show();
}
else if (nameResult === false || cityResult === false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
// })
});
</script>
</body>
</html>
I don't really know why your tests gives you an error, but I think your $('.form-control').each is useless.
In this foreach you test all your fields for each field.
Maybe try without this foreach, just test all your fields when you click on the button by removing this bit of code :
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
})
I don't see any other problem.
You have a syntax error I corrected that check below code.
function validateForm() {
var name_cityRegex = /^[a-zA-Z]+$/;
var emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
var age_phoneRegex = /^\d+$/;
var nameValue = $('#inputName').val();
var cityValue = $('#inputCity').val();
var ageValue = $('#inputAge').val();
var phoneValue = $('#inputPhone').val();
var nameResult = name_cityRegex.test(nameValue);
var cityResult = name_cityRegex.test(cityValue);
var ageResult = age_phoneRegex.test(ageValue);
var phoneResult = age_phoneRegex.test(phoneValue);
var mailValue = $('#InputEmail1').val();
var mailResult = emailRegex.test(mailValue);
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
else if (nameResult == false || cityResult == false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" name="name" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="text" name="age" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="text" name="city" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="text" name="email" class="form-control" id="InputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="text" name="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit" onClick="validateForm()">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>
I am working on trying to link pages together so if a person were to login using the login page, they would be redirected to a specific created page, and if a user clicked the register button, they would be redirected to the register page and from there, after inputting in information, they would be directed to another page. The button for login or register does not work. Is there a way to fix this?
So far I have this for my login page.
function login() {
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
ivar aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
window.location = "dashboard.php";
break;
}
}
var myOut = document.getElementById("output");
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
Validation function:
function validation() {
for (i=1; i<=10; i++) {
var myErr = document.getElementById("err" + i);
myErr.innerHTML = "";
}
document.getElementById("output").innerHTML = "";
var dept_name = document.getElementById("dept_name").value;
var user_email = document.getElementById("user_email").value;
var user_password = document.getElementById("user_password").value;
var phone_number = document.getElementById("phone_number").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var office_location = document.getElementById("office_location").value;
var valid = true;
if (dept_name == "") {
document.getElementById("err1").innerHTML = "Invalid!";
valid = false;
}
if ((user_email) =="") {
valid = false;
document.getElementById("err2").innerHTML = "Invalid!";
}
if ((user_password) =="") {
valid = false;
document.getElementById("err3").innerHTML = "Invalid!";
}
if ((first_name) =="") {
valid = false;
document.getElementById("err4").innerHTML = "Invalid!";
}
if ((last_name) =="") {
valid = false;
document.getElementById("err5").innerHTML = "Invalid!";
}
if (isNaN(phone_number) || card_number.length !==11) {
valid = false;
document.getElementById("err6").innerHTML = "Invalid!";
}
if ((office_location) =="") {
valid = false;
document.getElementById("err7").innerHTML = "Invalid!";
}
}
window.onload=init;
Several errors
missing brackets
no execution of init
missing validation function
This works:
function login() {
var myOut = document.getElementById("output");
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
var aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
myOut.innerHTML = "Correct - you will be redirected";
setTimeout(function() {
window.location = "dashboard.php";
},1000);
return;
}
}
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
}
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
function validation() { /* you need some code here */ }
window.onload=init;
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
You can make the test simpler:
var userPos = users.indexOf(aUser);
if (userPos !=-1 && userPos === pass.indexOf(aPass)) {
...
}
I am getting two values of checkbox one is always false with type hidden. I created a local storage and where I stored value of checkbox. I want to put values back into my form from local storage. Can somebody please help me with that.
$(document).ready(function() {
InitalizeCache(GetKey());
});
function GetKey() {
var key = "local";
return key;
}
function CacheSpikeData() {
var form = $("#application-form").serializeArray();
CacheData(form, GetKey());
}
function InitalizeCache(key) {
window.onload = function() {
RecoverFormFromLocalStorage(key);
}
}
function RecoverFormFromLocalStorage(key) {
if (localStorage.getItem(key) !== null) {
var recover = confirm("You have some unsaved changes. Do you want to continue from where you left? ");
if (recover == true) {
RecoverFormFromLocalStorage2(key);
return true;
} else {
clearLocalStorage(key);
return false;
}
}
}
function ShowSpikeData() {
alert(localStorage.getItem(GetKey()));
}
function LoadSpikeData() {
RecoverFormFromLocalStorage2(GetKey());
}
function clearLocalStorage(key) {
localStorage.removeItem(key);
}
function CacheData(jsoNform, key) {
localStorage.setItem(key, JSON.stringify(jsoNform));
}
function RecoverFormFromLocalStorage2(key) {
var cache = localStorage.getItem(key);
var record = JSON.parse(localStorage.getItem(key));
if (cache !== null) {
$("#application-form *").filter(':input').each(function() {
if (this.type != "hidden") {
var cache = localStorage.getItem(key);
var record = JSON.parse(localStorage.getItem(key));
var cacheValue = $(record).find("Name=MyStringValue");
this.value = cacheValue;
alert(this.name + this.hidden);
}
});
}
}
<html><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View - NumberFormattingSample</title>
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="/css/site.css">
</head>
<body>
<div class="container body-content">
<h2>View</h2>
<form id="application-form" action="/Test/EditCheckbox" method="post" novalidate="novalidate">
<div class="form-horizontal">
<h4>TestClass</h4>
<hr>
<div class="form-group">
<label class="col-md-2 control-label" for="MyStringValue">MyStringValue</label>
<div class="col-md-10">
<input id="MyStringValue" name="MyStringValue" value="" aria-invalid="false" class="valid" type="text">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="MyValue4">MyValue4</label>
<div class="col-md-10">
<div class="checkbox">
<input data-val="true" data-val-required="The MyValue4 field is required." id="MyValue4" name="MyValue4" value="true" type="checkbox">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="MyValue5">MyValue5</label>
<div class="col-md-10">
<div class="checkbox">
<input checked="checked" data-val="true" data-val-required="The MyValue5 field is required." id="MyValue5" name="MyValue5" value="true" type="checkbox">
</div>
</div>
</div>
<select>
<option>Option</option>
<option>Option1</option>
</select>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input value="Cache" type=button class="btn btn-default valid" onclick="CacheSpikeData()" aria-invalid="false">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input value="Show" type=button class="btn btn-default valid" onclick="ShowSpikeData()" aria-invalid="false">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input value="Load" type=button class="btn btn-default valid" onclick="LoadSpikeData()" aria-invalid="false">
</div>
</div>
</div>
<input name="__RequestVerificationToken" value="CfDJ8PubzbxcXzVMruNKDy4pjvN4hXQ65h4QOkv7uDsWo6fZ2L-XoEq_2ECU5X_vbG2E-06P5vqKof167EUuW9eWazRso-6D-lG8e74rUHikoOhsA_BVeWl4vx3OeutanaJtjbzs8RIpp4WuS74wbuf-5E0" type="hidden"><input name="MyValue4" value="false" type="hidden"><input name="MyValue5" value="false" type="hidden"></form>
<div>
Back to List
</div>
<hr>
<footer>
<p>© 2017 - NumberFormattingSample</p>
</footer>
</div>
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo"></script>
<script src="/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="/js/Caching.js"></script>
</body></html>
I am simply trying to insert values back to form without deleting the hidden value of checkbox, but picking up the current value.
Try changing InitalizeCache to this
function InitalizeCache(key) {
RecoverFormFromLocalStorage(key);
}
Rename RecoverFormFromLocalStorage2 to populateDataFromLocalStorage and change to this
function populateDataFromLocalStorage(key) {
var cache = localStorage.getItem(key);
if (cache !== null) {
var formJson = JSON.parse(cache);
$("#application-form *").filter(':input').each(function() {
var name = $(this).attr('name');
var formRecord = formJson.find(function(record) {
return name === record.name;
}) || {};
if (this.type === "text") {
$(this).val(formRecord.value);
}
if (this.type === "checkbox") {
$(this).prop('checked', formRecord.value === 'true');
}
});
}
}
Update LoadSpikeData() to call the correct function name populateDataFromLocalStorage
Also the inputs at the end should have type="button"
I'm trying to use form validation using JavaScript, however I don't seem to get any response, not even an alert even though it's there.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example Form</title>
<script type="text/javascript">
function CheckForBlank() {
if(document.getElementById('name').value="") {
alert("enter something valid");
return false;
}
}
</script>
</head>
<body>
<form method="post" action="2013.php" onsubmit="return CheckForBlank();">
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
Email: <input type="text" name="email" id="email"/>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
</html>
use === or == for condition checking in javascript.
if(document.getElementById('name').value === ""){
alert("enter something valid");
return false;
}
You have to use == for comparison.= is used for assigment
if(document.getElementById('name').value == ""){
alert("enter something valid");
return false;
}
Working Demo
Here Your issue is regarding if condition only! You must use == OR === in JavaScript for comparison.
Below is corrected script!
function CheckForBlank() {
if(document.getElementById('name').value=="") {
alert("enter something valid");
return false;
}
}
If you remove Or avoid return false, form will postback Even if Validation fails! So, return false means, exiting from function after if is must, and which is missed out in another answer!!
You are using = that is assignment operator, use == comparison operator that's work fine
<head>
<title>Example Form</title>
<script type="text/javascript">
function CheckForBlank() {
if(document.getElementById('name').value=="") {
alert("enter something valid");
return false;
}
}
</script>
</head>
<body>
<form method="post" onsubmit="return CheckForBlank();">
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
Email: <input type="text" name="email" id="email"/>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
I can't believe I've never realised this until now, although if you attach your Javascript to the form submission event, instead of the button submit event; the normal browser verification works (ie. input[type="email], required="required", etc.).
Works in Firefox & Chrome.
// jQuery example attaching to a form with the ID form
$(document).on("submit", "#form", function(e) {
e.preventDefault();
console.log ("Submitted! Now serialise your form and AJAX submit here...");
})
I have done a better way to do form validation using bootstrap. You can take a look at my codepen http://codepen.io/abhilashn/pen/bgpGRw
var g_UnFocusElementStyle = "";
var g_FocusBackColor = "#FFC";
var g_reEmail = /^[\w\.=-]+\#[\w\.-]+.[a-z]{2,4}$/;
var g_reCell = /^\d{10}$/;
var g_invalidFields = 0;
function initFormElements(sValidElems) {
var inputElems = document.getElementsByTagName('textarea');
for(var i = 0; i < inputElems.length; i++) {
com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
}
/* Add the code for the input elements */
inputElems = document.getElementsByTagName('input');
for(var i = 0; i < inputElems.length; i++) {
if(sValidElems.indexOf(inputElems[i].getAttribute('type') != -1)) {
com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
}
}
/* submit handler */
com_abhi.EVENTS.addEventHandler(document.getElementById('form1'), 'submit' , validateAllfields, false);
/* Add the default focus handler */
document.getElementsByTagName('input')[0].focus();
/* Add the event handlers for validation */
com_abhi.EVENTS.addEventHandler(document.forms[0].firstName, 'blur', validateFirstName, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].email, 'blur', validateEmailAddress, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].address, 'blur', validateAddress, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].cellPhone, 'blur', validateCellPhone, false);
}
function highlightFormElement(evt) {
var elem = com_abhi.EVENTS.getEventTarget(evt);
if(elem != null) {
elem.style.backgroundColor = g_FocusBackColor;
}
}
function unHightlightFormElement(evt) {
var elem = com_abhi.EVENTS.getEventTarget(evt);
if(elem != null) {
elem.style.backgroundColor = "";
}
}
function validateAddress() {
var formField = document.getElementById('address');
var ok = (formField.value != null && formField.value.length != 0);
var grpEle = document.getElementById('grpAddress');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('addressIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('addressErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('addressIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('addressErrorMsg').innerHTML = "Please enter your address";
}
return ok;
}
}
function validateFirstName() {
var formField = document.getElementById('firstName');
var ok = (formField.value != null && formField.value.length != 0);
var grpEle = document.getElementById('grpfirstName');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('firstNameIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('firstNameErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('firstNameIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('firstNameErrorMsg').innerHTML = "Please enter your first name";
}
return ok;
}
}
function validateEmailAddress() {
var formField = document.getElementById('email');
var ok = (formField.value.length != 0 && g_reEmail.test(formField.value));
var grpEle = document.getElementById('grpEmail');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('EmailIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('emailErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('EmailIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('emailErrorMsg').innerHTML = "Please enter your valid email id";
}
}
return ok;
}
function validateCellPhone() {
var formField = document.getElementById('cellPhone');
var ok = (formField.value.length != 0 && g_reCell.test(formField.value));
var grpEle = document.getElementById('grpCellPhone');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('cellPhoneErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('cellPhoneErrorMsg').innerHTML = "Please enter your valid mobile number";
}
}
return ok;
}
function validateAllfields(e) {
/* Need to do it this way to make sure all the functions execute */
var bOK = validateFirstName();
bOK &= validateEmailAddress();
bOK &= validateCellPhone();
bOK &= validateAddress();
if(!bOK) {
alert("The fields that are marked bold and red are required. Please supply valid\n values for these fields before sending.");
com_abhi.EVENTS.preventDefault(e);
}
}
com_abhi.EVENTS.addEventHandler(window, "load", function() { initFormElements("text"); }, false);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<h1 class="text-center">Interactive form validation using bootstrap</h1>
<form id="form1" action="" method="post" name="form1" class="form-horizontal" role="form" style="margin:10px 0 10px 0">
<div id="grpfirstName" class="form-group">
<label for="firstName" class="col-sm-2 control-label"><span class="text-danger">* </span>First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="firstName" placeholder="Enter first name">
<span id="firstNameIcon" class=""></span>
<div id="firstNameErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-sm-2 control-label">Last Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="lastName" placeholder="Enter last name">
</div>
</div>
<div id="grpEmail" class="form-group">
<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Email </label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" placeholder="Enter email">
<span id="EmailIcon" class=""></span>
<div id="emailErrorMsg" class="text-danger"></div>
</div>
</div>
<div id="grpCellPhone" class="form-group">
<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Cell Phone </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="cellPhone" placeholder="Enter Mobile number">
<span id="cellPhoneIcon" class=""></span>
<div id="cellPhoneErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group" id="grpAddress">
<label for="address" class="col-sm-2 control-label"><span class="text-danger">* </span>Address </label>
<div class="col-sm-10">
<textarea id="address" class="form-control"></textarea>
<span id="addressIcon" class=""></span>
<div id="addressErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
</form>
</div> <!-- End of row -->
</div> <!-- End of container -->
Please check my codepen to better understand code.