I'm working on a multi form using bootstrap.
In my validateForm function I have it so it adds an "Invalid" class if the input value is empty (user hasn't filled anything in)
Upon clicking next, the input gets a reddish background color, indicating the user hasn't filled anything in.
How do I remove the "Invalid" class when either:
User types something in the input field
OR
User clicks/focusses on the input field
Thus removing the reddish background color
JavaScript:
function validateForm() {
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
for (i = 0; i < y.length; i++) {
if (y[i].value == "") {
y[i].className += " invalid";
valid = false;
}
}
if (valid) { document.getElementsByClassName("step")[currentTab].className += " finish"; }
return valid;
}
CSS:
input.invalid {
background-color: #ffdddd;
}
Help is greatly appreciated!
Something like this:
document.getElementsByTagName("input").forEach(function(input) {
input.addEventListener("focus", function(event) {
input.classList.remove("invalid");
});
input.addEventListener("input", function(event) {
input.classList.remove("invalid");
});
});
Related
I wrote a custom JavaScript validator that needs to run on every keyup event that is attached to ever input and runs the vacillator() for every input field.
Problem is that it only works on load.
I want to to work on every key-up event.
Here is a jsfiddle https://jsfiddle.net/vo1npqdx/717/
function display_error(elem, message) {
elem.insertAdjacentHTML('afterend', "<label class='js-error' style='color:red;' >" + message + "</label>");
}
function check_error(elem) {
error_label = elem.nextElementSibling
if (error_label && error_label.classList.contains('js-error')) {
return true;
}
}
function add_error(elem,message) {
if (!check_error(elem)){
display_error(elem, message)
}
}
function delete_error(elem) {
if (check_error(elem)){
elem.nextElementSibling.remove();
}
}
function validateForm(elem) {
alert("Checking if form is vaild")
// If input type == text
if (elem.getAttribute("type") == 'text') {
//alert("elemcent is text")
maxlength = elem.getAttribute("maxlength")
minlength = elem.getAttribute("minlength")
data_error = elem.getAttribute("data-error")
// if has attribute maxlegnth
if (minlength) {
// if value is under min length
if (elem.value.length < parseInt(minlength)) {
// add errors
add_error(elem, data_error)
//alert("above min length")
} else {
// Delete
//alert("delere errror")
delete_error(elem)
}
}
}
// if input type == number
if (elem.getAttribute("type") == 'number') {
//alert("element is text")
max = elem.getAttribute("max")
min = elem.getAttribute("min")
data_error = elem.getAttribute("data-error")
// if has attribute maxlegnth
if (min) {
// if value is under min length
if (elem.value < parseInt(min)) {
// add errors
add_error(elem, data_error)
//alert("Belove Min Number")
}
else if(elem.value > parseInt(max)){
// add errors
add_error(elem, data_error)
//alert("above Max number")
}
else {
// Delete
//alert("delere errror")
delete_error(elem)
}
}
}
}
// Desired Result
// if keyup
// for input in inputs:
// someFunc(input) that makes input tags red
var inputs = document.getElementsByClassName('form-control');
for(var i=0;i<inputs.length;i++){
elem = inputs[i]
elem.addEventListener('keyup', validateForm(elem))
}
You are calling your event handler straight away. It needs to be wrapped with a function. So this:
elem.addEventListener('keyup', validateForm(elem))
should be:
elem.addEventListener('keyup', function(event) {
// do something with event
validateForm(this);
});
I am able to validate all fields within a div but I only want to validate specific fields. Here is a jsfiddle to show what I mean Once validation is passed the div is hidden. I have to enter data in all of the fields so if you check 'Yes' from the checkbox you will see a input field appear I don't want to include that and also if you select 'NoGame' from the dropdownlist once you enter data in all the fields apart from the two fields in the lower div (green border) and click the Test1 button you will see what I mean. Any suggestions?
This is the code which validates all fields and then Hides the div, which can also be seen in the fiddle
function IsValid(divid) {
var $div = $('#' + divid);
var result = true;
$.each($div.find("input[type='text']"), function (i, input) {
if ($(input).val().length == 0 || $.trim($(input).val()) == '') {
result = false;
return;
}
});
return result;
}
$(document).ready(function(){
$("#hide").click(function(){
if (IsValid('contentone')) {
$('#contentone').hide();
};
});
});
Input fields of type text that you don't want to validate exclude them from the validation process
function IsValid(divid) {
var $div = $('#' + divid);
var result = true;
var excludeElement = ["reason"]; //<-- EXCLUDED ELEMENTS IDS
$.each($div.find("input[type='text']"), function (i, input) {
if ($.inArray($(input).attr('id'), excludeElement) < 0 && ($(input).val().length == 0 || $.trim($(input).val()) == '')) {
result = false;
return;
}
});
return result;
}
How is it possible to display an alert with jQuery if I click the submit button and the value of the input field is empty?
<input type="text" id="myMessage" name="shoutbox_msg" size="16" class="field_nosize" maxlength="150">
<input id="submit" type="submit" name="submit_post" class="button_nosize" value="Senden" onclick="sendMessage(); clearInput();">
$('#submit').click(function(){
if($('#myMessage').val() == ''){
alert('Input can not be left blank');
}
});
Update
If you don't want whitespace also u can remove them using jQuery.trim()
Description: Remove the whitespace from the beginning and end of a string.
$('#submit').click(function(){
if($.trim($('#myMessage').val()) == ''){
alert('Input can not be left blank');
}
});
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
Also you can try this, if you want to focus on same text after error.
If you wants to show this error message in a paragraph then you can use this one:
$(document).ready(function () {
$("#submit").click(function () {
if($('#selBooks').val() === '') {
$("#Paragraph_id").text("Please select a book and then proceed.").show();
$('#selBooks').focus();
return false;
}
});
});
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
You could create a function that checks every input in an input class like below
function validateForm() {
var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
return $.trim(this.value).length === 0;
}).length > 0
if (anyFieldIsEmpty) {
alert("Fill all the necessary fields");
var empty = $(".myclass").filter(function () {
return $.trim(this.value).length === 0;
})
empty.css("border", "1px solid red");
return false;
} else {
return true;
}
}
What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.
Use this instead because just trying to check if the value is not equal to an empty string won't help if there are multiple spaces.
('#submit').onclick = function(){
let count = 0;
let notEmpty = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
for(let i=0; i < $('#myMessage').value.length; i ++){
for(let j = 0; j < notEmpty.length ; j++){
if($('#myMessage').value[i]== notEmpty[j]){
count += 1;
}
}
}
if(count==0){
alert("You cannot leave this blank");
}
}
How can I validate the radio field? It must be checked, if not checked, I would either like a err_radio441 to show up or an alert. I read some posts about checked but I am pulling from name because I know ID won't work. I am missing .checked or something. Any Help would be appreciated!
function validateForm() {
var primaryfullname=document.getElementById('primaryfullname').value.trim();
var birthdate=document.getElementById('birthdate').value.trim();
var radio441=document.getElementByName('radio441').value.trim();
var count=0;
if (primaryfullname.length==0) {
document.getElementById("err_primaryfullname").innerHTML="<br><span class='errorbar'>*You must enter a primary name</span>";
} else {
count++;
document.getElementById("err_primaryfullname").innerHTML="";
}
if (birthdate.length==0) {
document.getElementById("err_birthdate").innerHTML="<br><span class='errorbar'>*You must enter a primary birth date</span>";
} else {
count++;
document.getElementById("err_birthdate").innerHTML="";
}
if (radio441.length==0) {
document.getElementById("err_radio441").innerHTML="<br><span class='errorbar'>*You must select a gender</span>";
} else {
count++;
document.getElementById("err_radio441").innerHTML="";
}
if (count==3)
{
return true;
} else {
return false;
}
} // End Validation Function
Try using this:
var radio441 = document.getElementsByName('radio441');
// your other code
function checkRadio(elem){
for (var i = 0; i < elem.length; i++) {
if(elem[i].checked) return true;
}
return false;
}
if (!checkRadio(radio441)){
document.getElementById("err_radio441").innerHTML="<br><span class='errorbar'>*You must select a gender</span>";
} else {
count++;
document.getElementById("err_radio441").innerHTML="";
}
It loops through each radio button and returns true if any one of them is checked and false if none are.
if (!radio441.checked) {
// The radiobutton is not checked
} else {
// The radiobutton is checked
}
EDIT
To get the element by name you have to use document.getElementsByName('radio441')[0], assuming there's only one element with that name.
var radio441 = document.getElementsByName('radio441')[0];
if (!radio441.checked) {
// The radiobutton is not checked
} else {
// The radiobutton is checked
}
On
http://www.greekforme.com/999-apron-01.html, there are several Drop Down boxes.
The script called 'verifyselection' is supposed to show a pop-up box if the user does not change the drop down from 'Select an Option Below'
function verifyselection(form)
{
// result function
var blnResult = true;
// temp name form control
var nameControl = "";
// array of name of radio form controls
var arrNameControl = new Array();
// array of value checked of radio form controls
var arrValueControl = new Array();
// flag existence form control in array
var isExistOnArray = false;
// loop on all elements of form
for(i=0; i<form.elements.length; i++) {
// check type form control
if(form.elements[i].type=="radio") {
// save name form control
nameControl = form.elements[i].name;
// reset flag existence form control in array
isExistOnArray = false;
// loop on all found radio form control
for(j=0; j<arrNameControl.length; j++){
// if giving form control is exist in array
if(arrNameControl[j] == nameControl) {
// set flag
isExistOnArray = true;
// break loop
break;
}
}
// if giving form control is not exist in array
if(isExistOnArray == false){
// set index of array
j = arrNameControl.length;
// add new element to arrays
arrNameControl[j] = nameControl;
arrValueControl[j] = 0;
}
// if giving radio form control is checked
if(form.elements[i].checked == "1"){
arrValueControl[j] = 1;
}
}
if ((form.elements[i].selectedIndex > -1)) {
if (form.elements[i].selectedIndex == 0) {
var opttext = form.elements[i].value.toLowerCase();
if (opttext.indexOf('optional') < 0) {
blnResult = false;
alert('Please select one of the options from the list');
break;
}
}
}
}
// loop on all found radio form control
if(blnResult==true) {
for(j=0; j<arrNameControl.length; j++){
// if radio group form control is checked
if(arrValueControl[j] != 1) {
// set result function
blnResult = false;
// show error message
alert('Please select one of the options from the list');
break;
}
}
}
// return result function
return blnResult;
}
Currently, I can get the Pop-Up box to show when you click the Add to Cart button -
But... it still adds the items to cart.
I want the script to prevent the item from being added to cart if the user does not change the drop downs from 'Select an Option Below'
Where are you calling this function from? If it's in an onsubmit handler, the handler should return false. So, you should have this in your code somewhere:
form.onsubmit = function() {
return verifyselection(this);
}
Or, in html:
<form onsubmit="return verifyselection(this);" ...>
The important thing here being the return part. When the handler returns false, the default action won't be taken. In this case, the form won't submit.