Remove error validation on focus change in javascript - javascript

I'm beginner in javascript, so please bear with me.
I've a form in which i validate the controls with javascript. the error is displayed on clicking submit button when the fields are empty or where validation are not valid.
What I would like to do is to remove error message if i type in the right info in the field without clicking submit button.
const paragraph = document.querySelector('p');
const form = document.getElementById('create-account-form');
const usernameInput = document.getElementById('username');
form.addEventListener('submit', (event) => {
// btn.setAttribute('disabled', 'disabled');
validateForm();
console.log(isFormValid());
if (isFormValid() == true) {
form.submit();
} else {
event.preventDefault();
}
});
function isFormValid() {
const inputContainers = form.querySelectorAll('.input-group');
let result = true;
inputContainers.forEach((container) => {
if (container.classList.contains('error')) {
result = false;
}
});
return result;
}
function validateForm() {
//USERNAME
if (usernameInput.value.trim() == '') {
setError(usernameInput, 'Name can not be empty');
} else if (usernameInput.value.trim().length < 5 || usernameInput.value.trim().length > 15) {
setError(usernameInput, 'Name must be min 5 and max 15 charecters');
usernameInput.focus();
} else {
document.querySelector('p').textContent = "";
setSuccess(usernameInput);
}
}
function setError(element, errorMessage) {
const parent = element.parentElement;
if (parent.classList.contains('success')) {
parent.classList.remove('success');
}
parent.classList.add('error');
paragraph.textContent = errorMessage;
}
function setSuccess(element) {
const parent = element.parentElement;
if (parent.classList.contains('error')) {
parent.classList.remove('error');
}
parent.classList.add('success');
}
<form id="create-account-form" action="result.html" method="GET">
<div class="title">
<h2>Create Account</h2>
</div>
<!-- USERNAME -->
<div class="input-group">
<label for="username">Name</label>
<input type="text" id="username" placeholder="Name" name="username">
<p>Error Message</p>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>

You can use the input listener to do this.
See the codes below. I've done certain changes in the code.
modified your <input> as below.
<input type="text" id="username" placeholder="Name" name="username" oninput="validateForm(this)">
Read more about it in the docs
const paragraph = document.querySelector('p');
function isFormValid() {
const inputContainers = form.querySelectorAll('.input-group');
let result = true;
inputContainers.forEach((container) => {
if (container.classList.contains('error')) {
result = false;
}
});
return result;
}
function validateForm(usernameInput) {
//USERNAME
if (usernameInput.value.trim() == '') {
setError(usernameInput, 'Name can not be empty');
} else if (usernameInput.value.trim().length < 5 || usernameInput.value.trim().length > 15) {
setError(usernameInput, 'Name must be min 5 and max 15 charecters');
usernameInput.focus();
} else {
document.getElementById('error_p').textContent = "";
setSuccess(usernameInput);
}
}
function setError(element, errorMessage) {
const parent = element.parentElement;
if (parent.classList.contains('success')) {
parent.classList.remove('success');
}
parent.classList.add('error');
paragraph.textContent = errorMessage;
}
function setSuccess(element) {
const parent = element.parentElement;
if (parent.classList.contains('error')) {
parent.classList.remove('error');
}
parent.classList.add('success');
}
<form id="create-account-form" action="result.html" method="GET">
<div class="title">
<h2>Create Account</h2>
</div>
<!-- USERNAME -->
<div class="input-group">
<label for="username">Name</label>
<input type="text" id="username" placeholder="Name" name="username" oninput="validateForm(this)">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<p id="error_p">Error Message</p>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>

Related

Problem with required warning message and submit form

I'm implemented the code taken from here to check if radio button is checked and if not, see a warning message.
My code works, but I have a button for submit with ajax (jQuery(function($)) that go ahead also if radio input is not checked.
Some idea to avoid to run function jQuery if function validateForm() is validated?
Here my code:
document.getElementById("filter").onsubmit = validateForm;
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
jQuery(function($) {
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function(xhr) {
filter.find('button').text('Filtering...'); // changing the button label
},
success: function(data) {
filter.find('button').text('Filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis1(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis2(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br>
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action">
</div>
</form>
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
console.log(validateConsumo());
$(document).on("submit", "form#filter", function(e) {
e.preventDefault();
// Check for validations.
if (!validateConsumo()) {
console.log("Failed validation");
return;
}
console.log("Successful validation");
// Rest of the code here.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br />
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button type="submit" id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action" />
</div>
</form>
Remove document.getElementById("filter").onsubmit = validateForm;
and then update jQuery code like this:
$("#filter").on("submit", function (e) {
e.preventDefault();
// Check for validations.
if (!validateForm()) {
return;
}
// Rest of the code here.
});

Validation message doesn't show

Good day everyone! My problem is why the firstName & lastName error message not showing. The username & password error message is working fine. Even if the password and confirm password error is working fine. The only problem is when my firstName and lastName is empty no error message show. I already download the jQuery and include it to my head tag. I double check the id names if same with my html. I think there are same. Can somebody help me regarding to my problem? I will show you my codes below!
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
if (error_firstname = false && error_lastname = false) {
return true;
} else {
return false;
}
});
});
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>
This line is wrong:
if (error_firstname = false && error_lastname = false)
It's doing assignment, not comparison. Change that if/else to:
return !error_firstnames && !error_lastnames;
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
return !error_firstnames && !error_lastnames;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>

How to pass a value to a function and cont execute

I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem

Form Validation using JavaScript?

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.

Basic Validate javascript not working correctly

This is my simple code which I have been working to just show valid or invalid if the wrong text is inserted but the problem I’m having is that when I hit enter the valid and invalid flashes without staying on screen.
Here is my Fiddle
function validate ()
{
var me = document.getElementById("my").value;
if (me == 'my')
{
document.getElementById("Result").innerHTML = "valid";
document.getElementById("Result").style.color = "green";
}
else
{
document.getElementById("Result").innerHTML = "invalid";
document.getElementById("Result").style.color = "red";
}
}
<form>
<button type="button" onclick ="yes" class="fa fa-search"></button>
<input type="text" id="my" onchange="validate()"></input>
<label id="Result"></label>
</form>
What is the mistake i am doing and How can i fix this ?
The problem is that you have your code inside tag. You need to prevent form submission if you want to stay on the page.
I have not included CSS here!!
<div class="container">
<div id="nav">
<div id="search">
<form id="form1">
<button type="button" onclick ="yes" class="fa fa-search"></button>
<input type="text" id="my"></input>
<label id="Result"></label>
</form>
</div>
</div>
</div>
$(document).ready(function(){
$("#form1").submit(function(event){
if ( !validate()) {
alert("Error");
event.preventDefault();
return false;
}
});
});
function validate ()
{
var me = document.getElementById("my").value;
if (me == 'my')
{
document.getElementById("Result").innerHTML = "valid";
document.getElementById("Result").style.color = "green";
return true;
}
else
{
document.getElementById("Result").innerHTML = "invalid";
document.getElementById("Result").style.color = "red";
return false;
}
}
Here is a fiddle. Hope it will help.

Categories