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.
Related
$(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 this code that validates if ContentPlaceHolder1_locationTextBox has text in it before newIndex can become 3.
if ((newIndex === 3 && $("#ContentPlaceHolder1_locationTextBox").val() == "")) {
$('#ContentPlaceHolder1_locationLabelV').show();
return false;
}
else {
$('#ContentPlaceHolder1_locationLabelV').hide();
}
However I also have ContentPlaceHolder1_countryTextBox & ContentPlaceHolder1_seaTextBox on the page with thier respective labels, how can I modify the script so that it validates against all textboxes?
I tried adding a horrible or statement however this was causing the page to freeze. What s the best method to check against all three textboxes?
You can add class for all inputs, example: validate
After you can create JS function. You can fire this function as you wish.
function check(){
$('.validate').each(function(){
label = $("label[for='"+$(this).attr('id')+"']");
if ((newIndex === 3 && $(this).val() == "")) {
label.show();
return false;
}
else {
label.hide();
}
});
}
function validate(value) {
if ...
//show div
else ...
// hide div
}
$("input[type='text']").each(function(){
//value from input text field
var myval = $(this).val();
//call validation function
validate(myval);
});
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;
}
Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);
I have a form which contains couple fields. Its very easy to validate this form. But when I'm using append or clone comand and add couple more fields in it dynamically I cannot validate the appended fields.
Here is the my code:
function addone(container, new_div) {
var to_copy = document.getElementById(new_div);
$(to_copy).clone(true).insertAfter(to_copy);
}
And because it doesn't matter which fields and I want all of them get field out I used class instead of id.
$(document).ready(function(){
$('#add_size').live('click', function(){
if($('.inp').val() == "") {
alert('Need to fill-out all fields')
}
else {
alert('Thanks')
}
})
})
Any idea? Thanks in advance.
$(document).ready(function(){
$('#add_size').live('click', function(){
if( ! checkvalid() ) {
alert('Need to fill-out all fields')
}
else {
alert('Thanks')
}
})
})
function checkvalid(){
var valid = true;
$('.inp').each(function(){
if (this.value == '') {
valid = false;
return;
}
})
return valid;
}
I see one thing that might cause you trouble...:
If you're only going to check fields for validity on submit, then I don't think you need the live handler. You're not adding fields with #add_size, you're adding .inp's. Just do your validations on click, and jQuery should find all the .inp class fields that are there at the time of the event:
$('#add_size').click(function(
$('.inp').each ...
)};
Or maybe I totally read the question wrong...