$(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/
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.
I have a survey with two questions on the page (one that is multiple choice) and one that is a text entry question.
I want to hide the next button until the text entry question has been filled out but I've only been able to hide the next button indefinitely and it seems to not reappear after the text field has been filled in.
Qualtrics.SurveyEngine.addOnload(function()
{
this.hideNextButton();
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {hideNextButton ()} else {showNextButton ()}
});
});
});
You have some syntax errors. It looks like you are trying to use jQuery instead of Prototypejs. Besides that, you need to restrict your input element search to the question and there is only one input field so you only need one function. Try this (edited to defer initial next button hide):
Qualtrics.SurveyEngine.addOnload(function() {
function hideEl(element) {
element.hide();
}
var nb = $('NextButton');
hideEl.defer(nb);
$(this.questionId).down('.InputText').on('keyup', function(event) {
if(this.value.length == 0) nb.hide();
else nb.show();
});
});
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
}
});
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);
});
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();
}
});
);