Javascript validation - Error message only flashes for a second - javascript

I have this simple HTML project that validates an empty text and radiobutton field. The error is being displayed if one of the fields are empty, but the error message only flashes on the screen for a second, before disappearing again. Why is this happening?
Here's my HTML code
<form id="food_form">
<p>
<label>Your Name:
<input type="text" id="user_name" name="user_name">
</label>
<span id="error_user_name" class="error"></span>
</p>
<p>
Favorite Food?
<span id="error_radiobutton" class="error"></span><br>
<label><input type="radio" name="radiobutton" value="pizza">Pizza</label><br>
<label><input type="radio" name="radiobutton" value="burger">Burger</label><br>
<label><input type="radio" name="radiobutton" value="spaghetti">Spaghetti</label><br>
</p>
<input type="submit" value="Submit">
And then my Javascript code
<script>
document.getElementById("food_form").onsubmit = validateForm;
function validateForm() {
var validName = validateTextBox("user_name", "error_user_name"),
validRadiobutton = validateRadioButton();
}
function validateTextBox(fieldId, errorId) {
var text = document.getElementById(fieldId).value,
errorSpan = document.getElementById(errorId);
if (text === "") {
errorSpan.innerHTML = "* please input your name";
}
}
function validateRadioButton() {
var radiobutton = document.getElementById("food_form").radiobutton,
errorSpan = document.getElementById("error_radiobutton"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick something.";
}
}
Your response would be kindly appreciated.

Your function validateForm sets the error message but then you call validateRadioButton() which sets again errorSpan.innerHTML = "";. That is the reason of the "flash"

You are validating the form, but you need to return false if validation fails on submit event. Try this
function validateForm() {
var isTextBoxValid = validateTextBox("user_name", "error_user_name"),
isRadioButtonValid = validateRadioButton();
return isTextBoxValid || isRadioButtonValid;
}
function validateTextBox(fieldId, errorId) {
var text = document.getElementById(fieldId).value,
errorSpan = document.getElementById(errorId),
isValid = true;
if (text === "") {
errorSpan.innerHTML = "* please input your name";
isValid = false;
}
return isValid;
}
function validateRadioButton() {
var radiobutton = document.getElementById("food_form").radiobutton,
errorSpan = document.getElementById("error_radiobutton"),
isChecked = false, i,
errorSpan.innerHTML = "";
for (i = 0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick something.";
}
return isChecked;
}
In the above code we are returning Boolean value (true / false) for each of the functions and we are submitting the form if one of them is true

Try putting the submit button outside of the form element.
I've been having the same problem and this just worked for me.

Related

JS - How to stop form submission while text is empty AND checkbox is not ticked?

This is my script so far. The aim is to not allow submission while the text boxes are empty,
var chk = document.getElementsByName('termsChkbx')[0];
var btn = document.getElementsByName("submit")[0];
var fname = document.forms["bookingForm"]["forename"].value;
var sname = document.forms["bookingForm"]["surname"].value;
var cname = document.forms["bookingForm"]["companyName"].value;
document.getElementsByName('termsChkbx')[0].onclick = function() {
textCol()
};
function textCol() {
if (chk.checked) {
document.getElementById("termsText").style.color = "black";
document.getElementById("termsText").style.fontWeight = "normal";
btn.disabled = false;
if (fname == null || fname == "", sname == null || sname == "") {
btn.disabled = true;
}
}
else {
document.getElementById("termsText").style.color = "red";
document.getElementById("termsText").style.fontWeight = "bold";
btn.disabled = true;
}
}
I know there is something wrong with the logic in the second if statement, but I cant figure out how I can allow the button to be pressed when the box is ticked, but not allow it when the fields are empty.
<p><input type="submit" name="submit" value="Book now!" disabled=""></p>
Heres the HTML for the button, which I am unable to change. Any help would be appreciated.
I don't think you want to use , in if (fname == null || fname == "", sname == null || sname == ""). You could simplify it:
var chk = document.getElementsByName('termsChkbx')[0];
var btn = document.getElementsByName("submit")[0];
var fname = document.forms["bookingForm"]["forename"];
var sname = document.forms["bookingForm"]["surname"];
function validate() {
if(fname.value == "" || sname.value == "" || !chk.checked) {
btn.disabled = true
} else {
btn.disabled = false
}
}
validate()
chk.addEventListener("click", validate)
fname.addEventListener("change", validate)
sname.addEventListener("change", validate)
<form name="bookingForm">
<input type="text" name="forename">
<input type="text" name="surname">
<input type="checkbox" name="termsChkbx">
<input type="submit" value="Submit" name="submit">
</form>

InnerHTML in multiple fiields and more than one error statements

I am having trouble trying to get the form to validate using the onblur handler.
What I am trying to do is to get the first and last name field to display an error message if the field is blank, if it’s less than 5 , more than 18 characters, or it the user enters a number.
I would like to be able to do this using only one function so I do not need to do this for seperate functions.
Eg:
function ValidateName(field) {
var field = field.value;
var output = document.getElementById("fnameError");
if (field == "")
{
output = "field can’t be blank.";
return false;
}
else
{
output = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the question.
function ValidateName(field) {
var output = document.getElementById("fnameError");
if (field.value == "")
{
output.innerHTML = "field can’t be blank.";
}
else
{
output.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the the comment made on my answer.
function ValidateName() {
var outputF = document.getElementById("fnameError");
var outputL = document.getElementById("lnameError");
var outputB = document.getElementById("BothError");
var field1 = document.getElementById("Fname");
var field2 = document.getElementById("Lname");
if (field1.value == "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "No field can be left blank.";
outputL.innerHTML = "";
}
else if (field1.value !== "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "field can’t be blank.";
}
else if (field1.value == "" && field2.value !== "")
{
outputF.innerHTML = "field can’t be blank.";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
else {
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName()">
<span id="fnameError"></span>
<br><br>
<input type="Text" id="Lname" onblur="ValidateName()">
<span id="lnameError"></span>
<br><br>
<span id="BothError"></span>
</form>
you can try this also
function validateform(){
var name=document.myform.name.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(name.length < 5){
alert("name must be atleast 8 characters long");
return false;
}
else if(name.length <18){
alert("text must be more than 18 characters");
return false;
}
}
<form name="myform" method="post" action="" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
<input type="submit" value="register">
</form>

Check if all text inputs are empty, show alert with for if/else statement?

beginner here. I'm trying to use a conditional to check whether if the text inputs have been filled out, otherwise if empty, prompt an alert but it doesn't appear to do anything? Is my JS poorly laid out? Here is my jsfiddle. https://jsfiddle.net/rtomino/4ywq9n3n/2/
Thank you!!
<div>
<label for="cand1">Candidate 1</label>
<input class="candidate" id="cand1" placeholder="Candidate">
</div>
<div>
<label for="cand2">Candidate 2</label>
<input class="candidate" id="cand2" placeholder="Candidate">
</div>
<div>
<label for="cand3">Candidate 3</label>
<input class="candidate" id="cand3" placeholder="Candidate">
</div>
The JS
function candidateNames() {
var inputs = document.getElementsByTagName("input");
var result = [];
for ( var i = 0; i < inputs.length; i += 1 ) {
result[i] = inputs[i].value;
if (inputs === '' || null || 0) {
alert('Need to fill inputs');
}
}
document.getElementById("candidateName1").innerHTML = result[0];
document.getElementById("candidateName2").innerHTML = result[1];
document.getElementById("candidateName3").innerHTML = result[2];
}
You are checking if you inputs array is empty and not if the current input's value is empty.
See my inline comments.
function candidateNames() {
var inputs = document.getElementsByTagName("input");
var result = [];
for ( var i = 0; i < inputs.length; i += 1 ) {
result[i] = inputs[i].value;
if (inputs[i].value == '') { // check if value is empty
alert('Need to fill inputs');
return; // stop the function
}
}
document.getElementById("candidateName1").innerHTML = result[0];
document.getElementById("candidateName2").innerHTML = result[1];
document.getElementById("candidateName3").innerHTML = result[2];
}
//Event listener to calculate button to call all above functions
document.getElementById("btn").addEventListener("click", calculateVotes, false);
function calculateVotes() {
candidateNames();
}
You are checking for (inputs === '' || null || 0), which is wrong as inputs is an array, you need to do something like this:
function candidateNames() {console.log('here');
var inputs = document.getElementsByTagName("input");
var result = [];
for ( var i = 0; i < inputs.length; i += 1 ) {
result[i] = inputs[i].value;
if (results[i] === '' || null || 0) {
alert('Need to fill inputs');
}
}
document.getElementById("candidateName1").innerHTML = result[0];
document.getElementById("candidateName2").innerHTML = result[1];
document.getElementById("candidateName3").innerHTML = result[2];
}

check if input text field contains min val on submit

I have a pretty simple HTML web form...
I am taking the data and serializing to JSON (and will eventually send somewhere else. But, for now am using console.log for test).
When the user fills out the form, and then clicks submit; I would like to simply check the value of my input text field, and make sure the user has at-least entered a number higher then 0, but not 0.
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
I would like this validation to run before, my serialize function below it fires. Essentially, I want to check or validate this before data is sent. If the user enters 0, I don't want to send.
Below is my full JavaScript. (I still cannot get validate function as described above).
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
$('form').submit(function (e) {
function validateForm(){ // would like to check before below fires for serialize
var form = document.getElementById("form"), inputs = form.getElementsByTagName("input"),
input = null, flag = true;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
// if the value is not a valid number or it's less than or equal 0
if(isNaN(input.value) || +input.value < 0) {
flag = false;
input.focus();
console.log("error!");
// break;
}
}
return(flag);
}
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);
});
Simple validate number input. Try this.
$("#submit").on("click", function(){
inputValue = $("input[name='age']").val();
var num = parseInt(inputValue);
if(isNaN(num) || num <= 0){
console.log(inputValue + " Invalid number!");
} else {
console.log(inputValue + " Valid number!");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<input type="button" id="submit" value="Submit"\>
To accomplish that, I'm (more or less) usually do this:
HTML
<form action="(action url)" id="form" method="post" onsubmit="return validateForm()">
//form contents
</form>
JS
function validateForm() { // would like to check before below fires for serialize
//var form = document.getElementById("form"), inputs = form.getElementsByTagName("input"),
//If you use jQuery, it more preferred to write like this:
var form = $('#form'), inputs = form.find('input'), input = null, flag = true;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
// if the value is not a valid number or it's less than or equal 0
if(isNaN(input.value) || +input.value < 0) {
flag = false;
input.focus();
console.log("error!");
}
//do the break
if (!flag) break;
}
if (flag) {
var data = $(this).serializeFormJSON();
console.log(data);
}
return flag;
}

JavaScript Alert/Confirm Error

Currently when new users register at my website, they have to fill out some forms. If their password is too short, doesn't match, they don't fill out all of the fields, or any other error, I want to alert them of it. Currently it does not alert them, so I switched to confirm. That didn't work either so I considered using showModalDiaglog. That also didn't work, I am out of Ideas. I currently have this:
HTML
<form>
First Name:<br/> <input id="firstname"/><br/>
Last Name: <br/> <input id="lastname"/><br/>
Age: <br/> <input id="age"/><br/>
Your Email:<br/> <input id="email"/><br/>
Username: <br/> <input id="username"/><br/>
Password: <br/> <input id="password"/><br/>
Confirm Password:<br/> <input type="password" id="passwordconfirm"/><br/>
<br/>
<button size=20 onClick='getRegistrationFields()'>Submit</button>
</form>​
JavaScript
function getRegistrationFields() {
var first = document.getElementById("firstname").value;
var last = document.getElementById("lastname").value;
var email = document.getElementById("email").value;
var age = document.getElementById("age").value;
var username = document.getElementById("username").value;
var password = document.getElemetnById("password").value;
var confirm = document.getElementById("passwordconfirm").value;
var empty = "";
if ((first === empty) || (last === empty) || (email === empty) || (age === empty)
|| (username === empty) || (password === empty) || (confirm === empty)) {
var message = "Not all of the fields are filled out";
prompt(message);
//showModalWindow("fields");
return false;
}
else {
age = parseInt(age);
if (password.length < 10) {
var message2 = "Password must be at least 10 characters long";
prompt(message2);
//showModalWindow("passwordlength");
return false;
}
else if (password != confirm) {
var message3 = "Passwords Do not match";
prompt(message3);
//showModalWindow("passwordmatch");
return false;
}
else if (age < 18) {
var message4 = "You must be older to register for this software.";
prompt(message4);
//showModalWindow("young");
return false;
}
else {
var message5 = "All of the fields are correct. We will be processing your request";
prompt(message5);
//showModalWindow("success");
return true;
}
}
}
function showModalWindow(fileName) {
window.showModalDialog("alerts/" + url + ".html", "", "resizable: no; height: 150; width: 350;");
}
try
html:
<button size="20" id="btn_submit">Submit</button>
js:
var btn_submit = document.getElementById("btn_submit");
btn_submit.onclick = getRegistrationFields;
Make it easy on yourself.
<input type="password" class="password" />
<input type="text" class="age" />
<script type="text/javascript">
!(function () {
var txBxs = document.querySelectorAll('input[type=textbox]'),
i = txBxs.length;
while (i--) {
tkBxs[i].onchange = textBoxCheck;
};
}());
//
function textBoxCheck() {
//
switch (this.class) {
//
case 'password':
if (this.value.length < 10)
{ alert('Password to short'); };
break;
//
case 'age':
if (+this.value < 18)
{ alert('To young kiddo!'); };
break;
};
};
</script>
There is a typo:
var password = document.getElemetnById("password").value;
You wrote getElemetnById instead of getElementById.

Categories

Resources