Currently my code checks for input in the textareas on the site. If I leave all of them blank, they all get highlighted red when I press the button, which is expected. But, when I enter text into 1 or more boxes, it just passes through.
It isn't checking all the boxes everytime I press the button, it validates the submit if 1 box has text in it. What is wrong with the js code?
$(window).load( function () {
$('#form1').on('submit', function(event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
});
function validate() {
var success = true;
// Verify that the user entered some special instructions (we only take special orders!)
var inputarea = $('.input');
for(var i = 0; i < inputarea.length; i++)
{
if(inputarea.val() === "")
{
console.log("Missing textarea input");
success = false;
//NEED TO CHANGE THE LINE BELOW SO IT WONT SHOW TEXT, JUST CHANGE BORDER COLOUR
$('.input').css("border","1px solid red");
}
}
return success;
}
});
http://jsfiddle.net/originalwill/5cw1a2c2/
The link won't show my error because it is based on a button request using a form, so it won't work in jsFiddle.
I believe the following would be a better solution:
function validate() {
var success = true;
// Verify that the user entered some special instructions (we only take special orders!)
$('.input').each(function(i, item) {
if ($(item).val() === "") {
console.log("Missing textarea input");
success = false;
//NEED TO CHANGE THE LINE BELOW SO IT WONT SHOW TEXT, JUST CHANGE BORDER COLOUR
$(item).css("border","1px solid red");
}
});
return success;
}
In your original code, you had the statement:
if (inputarea.val() === "")
Notice that this had no relationship to your indexing through the array. It might have worked with something like the following:
if ($(inputarea.get(i)).val === "")
which would have obtained the element for the i'th entry and then retrieved its value but I believe the jQuery.each() function is superior for your task.
A sample jsFiddle is provided.
in native javascript
var inputarea = documen.getElementsByClassName('input');
for(var i = 0; i < inputarea.length; i++)
{
if(inputarea[i].value === "")
{
console.log("Missing textarea input");
success = false;
inputarea[i].style.border='1px solid red';
// or inputarea[i].style = 'border:1px solid red;';
}
}
in Jquery i think this will work
$('.input').each(function(i, item) {
if ($(item).val() === "") {
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}else{
$(item).removeAttr('style')
// to remove border
}
});
Related
I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.
Is it possible to check via jQuery or vanilla JS if an element has a specific style?
In my case I want to check if any input-fields on the page have a red border — applied via an external CSS-File. No inline-css and no style-attr is available, styling is completely external.
For my initial testing I got the following code from this StackOverflow-Answer: https://stackoverflow.com/a/29659187
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var res = $('.formValidation input[type=text],.formValidation input[type=email],.formValidation input[type=url],.formValidation input[type=password]').toArray().some(function(el){
return $(el).css('border-color') === 'rgb(255,0,0)'
});
if (res) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
… but .css seams to only test inlineStyles.
Update
I can't change HTML, the markup has to stay «as is». The red border is coming through css only. Like this: https://jsfiddle.net/z3t6k04s/
Try it like this:
$('.formValidation input[type=submit]').on('click',function(e){
// Prevent Default Form Submit
e.preventDefault();
// Define Global if Invalid Fields Exist
var hasInvalidInputs = false;
// Run Through all to check Input Fields
$('input').filter(function(index){
// Check if Invalid Inputs already got detected. If not - check if this field is red
if( !hasInvalidInputs )
hasInvalidInputs = $(this).css('border-color') == 'rgb(161, 0, 0)'; // If field is red -> update global var to true
});
// Check if Invalid Fields are set to true
if (hasInvalidInputs) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
You could use
Window.getComputedStyle()
The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
Example:
var inp = document.getElementsByTagName('input')[0];
var style = window.getComputedStyle(inp, null);
console.log(style.getPropertyValue("border-color"))
input[type='text'] {
border: 1px solid rgb(255, 0, 0);
}
<input type="text" value="Foo" />
Create a one class which has a red color
like
.red-color{
border-color:red;
}
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var res = $('.formValidation input[type=text],.formValidation input[type=email],.formValidation input[type=url],.formValidation input[type=password]').toArray().some(function(el){
return $(el).hasClass('red-color');
});
if (res) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
I hope this will helpful to you.
You can use below code
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var isValid;
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
element.css('border-color','red');
}else{
isValid = true;
element.css('border-color','');
}
});
if (isValid==false) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
I would like to get this function to check the email text box after the textbox has lost focus and not as soon as the user starts to type. So it only guides them after an error in the text box happens on .emailError textbox class.
I really don't want it to start showing error class till after the first try. Only to show green when the correct input has taken place.
var c = 0;
c = parseInt("c");
$('.emailError').on('focusout', function() {
c = 1;
});
if (c == 1) {
$('.emailError').on('keyup focusout', function() {
var regex = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
var containsNonEmail = this.value.match(regex);
console.log(containsNonEmail);
if (!containsNonEmail) {
$(".wirelessEmail").css("border", "2px solid #ffeef6");
$(".wirelessEmail").css("background-color", "#ffecf2");
} else {
$(".wirelessEmail").css("border", "2px solid green");
$(".wirelessEmail").css("background-color", "#f5fef2");
}
});
}
You need to have the if else check inside of the function and not on the outside. When it is outside, you will not bind the event.
Better way would be to do the checking so you do not rely on a global variable, this way you could use it more than once on the page. To do that use a data attribute.
$('.emailError').on('keyup focusout', function(evt) {
var tb = $(this);
var once = tb.data("once");
if(evt.type==="focusout" || once) {
if (!once) tb.data("once", "true");
var isError = tb.val().length<5;
tb.toggleClass("error", isError);
}
})
.error { background-color : red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="emailError" />
Use the Onblur function
The onblur event occurs when an object loses focus.
The onblur event is most often used with form validation code (e.g. when the user leaves a form field).
$(document).ready( function()
{
// hides the story and error text when the page loads
$('.errorText').hide();
$("#story").hide();
// global variables for the blanks and the textarea forms
var input = $("form").children();
var storyBlank = $('#story').children();
// Main Event on Click
$('button.submit').on( "click", function (event)
{
// if the form is not validated, highlights errors and prevents the submit from going through
if(!validate())
{
event.preventDefault();
}
// if the form is validated, fills the blanks in the story and displays it
else
{
fillInTheBlanks();
}
});
// Checks to see if there are any empty fields and highlights them if they are empty
function validate()
{
console.log('validate() initiated')
var success = false;
errcnt = 0;
cnt = 0;
while (cnt < 9)
{
if (input.eq(cnt).val().length == 0)
{
errcnt++;
input.eq(cnt).removeClass("hide");
console.log('errorcount', errcnt, 'at input', cnt);
}
else if (input.eq(cnt).val().length !== 0 && !(input.eq(cnt)).hasClass("hide"))
{
input.eq(cnt).addClass("hide");
}
cnt++;
}
if (errcnt == 0)
{
success = true;
}
return success;
}
// Fills in the blanks of the story
function fillInTheBlanks()
{
console.log('fillInTheBlanks() executed');
var blankCount = 0;
while (blankCount < 9)
{
storyBlank.eq(blankCount).empty().append(input.eq(blankCount).val());
blankCount++;
}
$("#story").show();
}
});
I am trying to make a mad libs style page with 9 textboxes for input. I am running into two problems.
First, when I click submit with all textboxes empty, only the the first four show an error (this is done in css, I have two classes on all the textboxes "error hide", I remove the class hide in my loop to show the error).
The second problem I'm having is if I click submit with text in all the textboxes, my validate functions errorcount goes up to 4 errors at every other textbox. I've even tried '$('input').eq(0).val().length == 0' for every textbox in the index and it's returning false every time. I don't understand how it's getting into that if then statement if it doesn't satisfy the argument.
i don't understand your problem, but if is validation on inputs empty... using
http://parsleyjs.org/
I have a site using input:text, select and select multiple elements that generate a text output on button click.
Having searched SO, I found examples of validation code that will alert the user when a select field returns an empty value-
// alert if a select box selection is not made
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
$(this).addClass("highlight");
}
At the end, I tried to add a condition after the alert is dismissed, such that the offending select box will be highlighted by adding the 'highlight' class - but this doesn't do anything. My .highlight css is {border: 1px red solid;}
Any help here?
UPDATED WITH ANSWER - Thanks #Adam Rackis
This code works perfectly. I added a line to remove any added '.highlight' class for selects that did not cause an error after fixing
// alert if a select box selection is not made
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
$('select').removeClass("highlight");//added this to clear formatting when fixed after alert
var anyInvalid = false;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
$(selectEls[x]).addClass("highlight");
anyInvalid = true;
}}
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
You were close. In your loop, this does not refer to each select that you're checking.
Also, you're returning false prior to the highlight class being added. You'll probably want to keep track of whether any select's are invalid, and return false at the very end after you're done with all validation.
Finally, consider moving your alert to the very bottom, so your user won't see multiple alerts.
var anyInvalid = false;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
$(selectEls[x]).addClass("highlight");
anyInvalid = true;
}
}
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
Also, since you're already using jQuery, why not take advantage of its features a bit more:
$('select').each(function(i, sel){
if (sel.value === '') {
$(el).addClass("highlight");
anyInvalid = true;
}
});
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}