Show div when all fields are filled - javascript

i am trying to show a div when all inputs are filled , but unfortunately it shows nothing here is my JS , it works on the JS FIDDLE but not on the website
$('#name, #prenom, #password,#confirm_password, #email,#confirm_email').bind('keyup', function() {
if(allFilled()) $('.next2').show();
});
function allFilled() {
var filled = true;
$('body input').each(function() {
if($(this).val() == '') filled = false;
});
return filled;
}

You can turn the jQuery collection into an an array and then use the native JS array method every to check to see if all the inputs contain values.
const inputs = $('input');
inputs.on('keyup', function() {
const notEmpty = inputs.toArray().every(input => {
return input.value !== '';
});
if (notEmpty) {
$('div').show();
} else {
$('div').hide();
}
});
div { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<input />
<input />
<input />
<div>All the values!</div>

Related

How to alert user for blank form fields?

I have this form that has 3 inputs and when a user leaves a field blank a dialogue box pops up to alert the user a field is blank. The code I have below only works for 2 specific input. When i try adding another input to the code it doesnt work. It only works for 2 inputs. How can I make it work for all three?
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Your Google Map's mileage\n";
}
if(location=='' )
{
missingFields = true;
strFields += " Your business name\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
Showing 3 alerts may be disturbing, use something like this:
$(document).on('submit', 'form', function () {
var empty = $(this).find('input[type=text]').filter(function() {
return $.trim(this.value) === "";
});
if(empty.length) {
alert('Please fill in all the fields');
return false;
}
});
Inspired by this post.
Or you can do validation for each field this way using HTML data attributes:
<form data-alert="You must provide:" action="" method="post">
<input type="text" id="one" data-alert="Your Google Map's mileage" />
<input type="text" id="two" data-alert="Your business name" />
<input type="submit" value="Submit" />
</form>
... combined with jQuery:
$('form').on('submit', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find('input[type=text]').each(function(i) {
var thisInput = $(this);
if ( !$.trim(thisInput.val()) ) {
thisAlert += '\n' + thisInput.data('alert');
canSubmit = false;
};
});
if( !canSubmit ) {
alert( thisAlert );
return false;
}
});
Take a look at this script in action.
Of course, you can select/check only input elements that have attribute data-alert (which means they are required). Example with mixed input elements.
You can add the required tag in the input fields. No jQuery needed.
<input required type="text" name="name"/>
Try this
var fields = ["a", "b", "c"]; // "a" is your "mile"
var empties= [];
for(var i=0; i<fields.length; i++)
{
if(!$('#'+fields[i]).val().trim())
empties.push(fields[i]);
}
if(empties.length)
{
alert('you must enter the following fields '+empties.join(', '));
return false;
}
else
return true;
instead of this
var name = $('#mile').val();
if (!name.trim()) {
alert('you must enter in your mile');
return false;
}

Javascript validation - group validation - if one entered, then all required

Using just jQuery (not validation plugin) I have devised a way to do a "if one, then all" requirement, but it's not at all elegant.
I'm wondering if someone can come up with a more elegant solution? This one uses some loop nesting and I'm really not pleased with it.
if ($("[data-group]")) {
//Store a simple array of objects, each representing one group.
var groups = [];
$("[data-group]").each(function () {
//This function removes an '*' that is placed before the field to validate
removeCurError($(this));
var groupName = $(this).attr('data-group');
//If this group is already in the array, don't add it again
var exists = false;
groups.forEach(function (group) {
if (group.name === groupName)
exists = true;
});
if (!exists) {
var groupElements = $("[data-group='" + groupName + "']");
var group = {
name: groupName,
elements: groupElements,
trigger: false
}
group.elements.each(function () {
if (!group.trigger) {
group.trigger = $(this).val().length !== 0;
}
});
groups.push(group);
}
});
//Now apply the validation and alert the user
groups.forEach(function (group) {
if (group.trigger) {
group.elements.each(function () {
//Make sure it's not the one that's already been filled out
if ($(this).val().length === 0)
// This function adds an '*' to field and puts it into a
// a sting that can be alerted
appendError($(this));
});
}
});
You don't have to store the groups in an array, just call the validateGroups function whenever you want to validate the $elements. Here is a working example http://jsfiddle.net/BBcvk/2/.
HTML
<h2>Group 1</h2>
<div>
<input data-group="group-1" />
</div>
<div>
<input data-group="group-1" />
</div>
<h2>Group 2</h2>
<div>
<input data-group="group-2" value="not empty" />
</div>
<div>
<input data-group="group-2" />
</div>
<div>
<input data-group="group-2" />
</div>
<button>Validate</button>
Javascript
function validateGroups($elements) {
$elements.removeClass('validated');
$elements.each(function() {
// Return if the current element has already been validated.
var $element = $(this);
if ($element.hasClass('validated')) {
return;
}
// Get all elements in the same group.
var groupName = $element.attr('data-group');
var $groupElements = $('[data-group=' + groupName + ']');
var hasOne = false;
// Check to see if any of the elements in the group is not empty.
$groupElements.each(function() {
if ($(this).val().length > 0) {
hasOne = true;
return false;
}
});
// Add an error to each empty element if the group
// has a non-empty element, otherwise remove the error.
$groupElements.each(function() {
var $groupElement = $(this);
if (hasOne && $groupElement.val().length < 1) {
appendError($groupElement);
} else {
removeCurError($groupElement);
}
$groupElement.addClass('validated');
});
});
}
function appendError($element) {
if ($element.next('span.error').length > 0) {
return;
}
$element.after('<span class="error">*</span>');
}
function removeCurError($element) {
$element.next().remove();
}
$(document).ready(function() {
$('button').on('click', function() {
validateGroups($("[data-group]"));
});
});
You might get some milage out of this solution. Basically, simplify and test your solution on submit click before sending the form (which this doesn't do). In this case, I simply test value of the first checkbox for truth, and then alert or check the required boxes. These can be anything you like. Good luck.
http://jsfiddle.net/YD6nW/1/
<form>
<input type="button" onclick="return checkTest()" value="test"/>
</form>
and with jquery:
checkTest = function(){
var isChecked = $('input')[0].checked;
if(isChecked){
alert('form is ready: input 0 is: '+isChecked);
}else{
$('input')[1].checked = true;
$('input')[2].checked = true;
}
};
//create a bunch of checkboxes
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');

Validating HTML input elements inside a DIV (visible wizard step) which is inside a FORM?

I have decided to create a wizard form in HTML 5 (actually using ASP.NET MVC here). I have the following HTML form:
#using (Html.BeginForm())
{
<div class="wizard-step">
<input type="text" name="firstname" placeholder="first name" />
</div>
<div class="wizard-step">
<input type="text" name="lastname" placeholder="last name" />
</div>
<div class="wizard-step">
<input type="text" name="suffix" placeholder="suffix" />
</div>
<button class="back-button" type="button">
Back</button>
<button class="next-button" type="button">
Next</button>
}
Then I have this js script:
<script type="text/javascript">
$(document).ready(function () {
var $steps = $(".wizard-step");
var index = 0;
var count = $steps.length;
$steps.each(function () {
$(this).hide();
});
$(".back-button").attr("disabled", "disabled");
var $currentStep = $steps.first();
$currentStep.show();
$currentStep.addClass("current-step");
$(".back-button").click(function () {
$currentStep.hide();
$currentStep.removeClass("current-step");
$currentStep = $currentStep.prev();
$currentStep.addClass("current-step");
$currentStep.show();
index--;
$(".next-button").removeAttr("disabled");
if (index == 0) {
$(this).attr("disabled", "disabled");
}
else {
$(this).removeAttr("disabled");
}
});
$(".next-button").click(function () {
var $inputFields = $(".current-step :input");
var hasError = false;
$inputFields.each(function () {
if (!validator.element(this)) {
hasError = true;
}
});
if (hasError)
return false;
index++;
$(".back-button").removeAttr("disabled");
if (index == count - 1) {
$(this).attr("disabled", "disabled");
}
else {
$(this).removeAttr("disabled");
}
$currentStep.hide();
$currentStep.removeClass("current-step");
$currentStep = $currentStep.next();
$currentStep.addClass("current-step");
$currentStep.show();
});
});
</script>
Basically, what I want is upon clicking the Next button, it will validate the input elements found inside the current visible DIV, not the entire FORM. Is it possible to do this using HTML5? If not, maybe jQuery?
If you have others in mind, please do share it here. Many many thanks!
after some playing with the jquery i happened to find the solution despite of lack of samples and tutorials in validation. inside the $(".next-button").click() block, i made these changes:
old:
var hasError = false;
$inputFields.each(function () {
if (!validator.element(this)) {
hasError = true;
}
});
if (hasError)
return false;
new:
var isValid = false;
$inputFields.each(function () {
isValid = $(this).valid();
});
if (!isValid)
return false;
======================
i could also add this right under the $(document).ready() line to use/add jquery validation rules:
$("#myForm").validate({
rules: {
lastname: "required"
}
});

JS: default text swap with live new element added

So for default text swapping on input (or other type of el) I have this snippet
<input class="js_text_swap" type="text" value="Enter your email" />
if($('.js_text_swap').length > 0) {
$('.js_text_swap').each(function() {
var that = $(this),
value = that.val(); // remembering the default value
that.focusin(function() {
if(that.val() === value) {
that.val('');
}
});
that.focusout(function() {
if(that.val() === '') {
that.val(value);
}
});
});
}
So my questions are:
1) does anybody has a better solution for this?
2) does anyone know how to make this work with live added elements (added with js after page has loaded)?
Thanks
Jap!
HTML
<input placeholder="Click..." class="text" type="text">
CSS
.text{color:#aaa}
.text.focus{color:#444}
JS
$("input[placeholder]").each(function() {
var placeholder = $(this).attr("placeholder");
$(this).val(placeholder).focus(function() {
if ($(this).val() == placeholder) {
$(this).val("").addClass('focus');
}
}).blur(function() {
if ($(this).val() === "") {
$(this).val(placeholder).removeClass('focus');
}
});
});
http://yckart.com/jquery-simple-placeholder/
UPDATE
To make it work with ajax or similar you need to convert it into a "plugin" and call it after your succesed ajax request (or after dynamically crap creating).
Something like this (very simple example):
jQuery.fn.placeholder = function() {
return this.each(function() {
var placeholder = $(this).attr("placeholder");
$(this).val(placeholder).focus(function() {
if ($(this).val() == placeholder) {
$(this).val("").addClass('focus');
}
}).blur(function() {
if ($(this).val() === "") {
$(this).val(placeholder).removeClass('focus');
}
});
});
};
$("input:text, textarea").placeholder();
$("button").on("click", function() {
$(this).before('<input type="text" placeholder="default value" />');
$("input:text, textarea").placeholder();
});
demo

<input type="text"> helper (fades out the text when user types) javascript

I want to add helpful text (in javascript WITHOUT ANY FRAMEWORK USE) in input fields text and textarea something like this but dont know what its called
As it is used in me.com but I dont want to submit the values that are used as helpers.
Sorry for bad english.
Thank You.
Easiest way:
<input type=text placeholder="Member name">
Try this:
<input type="text" name="member_name" value="Member Name" onFocus="field_focus(this, 'Member Name');" onblur="field_blur(this, 'Member Name');" />
Ofcourse, you would like to create input type password for the password field, so this won't be useful for the password text box.
You can also wrap this in functions if you are dealing with multiple fields:
<script type="text/javascript">
function field_focus(field, text)
{
if(field.value == text)
{
field.value = '';
}
}
function field_blur(field, text)
{
if(field.value == '')
{
field.value = text;
}
}
</script>
I've found that the best way to solve this is to use an <label> and position it over the input area. This gives you:
More aesthetic freedom
Keeps your page semantic
Allows you to gracefully degrade
Doesn't cause problems by submitting the tooltip as the input value or have to worry about managing that problem
Here's a vanilla version since you asked for no framework. The markup shouldn't need to change, but you may need to adjust the CSS to work with your needs.
HTML:
<html>
<head>
<style>
label.magiclabel {
position: absolute;
padding: 2px;
}
label.magiclabel,
input.magiclabel {
width: 250px;
}
.hidden { display: none; }
</style>
<noscript>
<style>
/* Example of graceful degredation */
label.magiclabel {
position: static;
}
</style>
</noscript>
</head>
<body>
<label>This is not a magic label</label>
<form>
<label class="magiclabel" for="input-1">Test input 1</label>
<input class="magiclabel" type="text" id="input-1" name="input_1" value="">
<label class="magiclabel" for="input-2">Test input 2 (with default value)</label>
<input class="magiclabel" type="text" id="input-2" name="input_2" value="Default value">
</form>
<script src="magiclabel.js"></script>
</body>
</html>
vanilla-magiclabel.js
(function() {
var oldOnload = typeof window.onload == "function" ? window.onload : function() {};
window.onload = function() {
// Don't overwrite the old onload event, that's just rude
oldOnload();
var labels = document.getElementsByTagName("label");
for ( var i in labels ) {
if (
// Not a real part of the container
!labels.hasOwnProperty(i) ||
// Not marked as a magic label
!labels[i].className.match(/\bmagiclabel\b/i) ||
// Doesn't have an associated element
!labels[i].getAttribute("for")
) { continue; }
var associated = document.getElementById( labels[i].getAttribute("for") );
if ( associated ) {
new MagicLabel(labels[i], associated);
}
}
};
})();
var MagicLabel = function(label, input) {
this.label = label;
this.input = input;
this.hide = function() {
this.label.className += " hidden";
};
this.show = function() {
this.label.className = this.label.className.replace(/\bhidden\b/ig, "");
};
// If the field has something in it already, hide the label
if ( this.input.value ) {
this.hide();
}
var self = this;
// Hide label when input receives focuse
this.input.onfocus = function() {
self.hide();
};
// Show label when input loses focus and doesn't have a value
this.input.onblur = function() {
if ( self.input.value === "" ) {
self.show();
}
};
// Clicking on the label should cause input to be focused on since the `for`
// attribute is defined. This is just a safe guard for non-compliant browsers.
this.label.onclick = function() {
self.hide();
};
};
Vanilla demo
As you can see, about half of the code is wrapped up in the initialization in the window.onload. This can be mitigated by using a framework. Here's a version using jQuery:
$(function() {
$("label.magiclabel[for]").each(function(index, label) {
label = $(label);
var associated = $("#" + label.attr("for"));
if ( associated.length ) {
new MagicLabel(label, associated);
}
});
});
var MagicLabel = function(label, input) {
// If the field has something in it already, hide the label
if ( input.val() !== "" ) {
label.addClass("hidden");
}
label.click(function() { label.addClass("hidden"); });
input.focus(function() { label.addClass("hidden"); });
input.blur(function() {
if ( input.val() === "" ) {
label.removeClass("hidden");
}
});
};
jQuery demo. The markup doesn't need to be changed, but of course you'll need to include the jQuery library.

Categories

Resources