I have a form having few questions set, each displayed at a time (like a slide). I want to prevent next set if current set has an empty field. Below is my script that navigates through each questions set. Any help would be highly appreciated.
$(document).ready(function() {
var $questions = $('#questions .question');
var currentQuestion = $('#questions .question.active').index();
$('#next').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion++;
if (currentQuestion == $questions.length - 1) {
$('#next').css('display', 'none');
$('#submit').css('display', 'inline');
}else{
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
}
$('#back').css('display', 'inline');
$($questions[currentQuestion]).slideDown();
});
});
$('#back').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion--;
if (currentQuestion == 0) {
$('#back').css('display', 'none');
} else {
$('#back').css('display', 'inline');
}
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
$($questions[currentQuestion]).slideDown();
});
});
});
Here is my JSFiddle
I came across your question and decided to fork your fiddle.
You should make a function that checks your conditions before continuing on to the next tab.
In your case, the conditions would be: All fields must be filled
I've added this function that checks the active section and returns true / false, in order to continue.
function validateFormSection() {
var valid = true; //As long as it's true, we may continue
var section = $('.question.active'); //Find the active section
var inputs = section.find('input'); //Get all its inputs
inputs.each(function(index, el) {
if ( $(el).val() == "" ) {
valid = false;
}
});
return valid;
}
JSFiddle here
On the third page, the form would submit whether all fields are empty or not.
You can prevent this by hooking onto the submit function and checking for empty fields.
If they're empty, we use e.preventDefault(); to keep it from submitting.
If they're filled, we simply submit by doing $('form').submit();
$('form').submit( function (e) { //Hook into the submit event
var valid = validateFormSection(); //Check if our fields are filled
if ( valid ) { //They are filled?
$('form').submit(); //Very well, let's submit!
} else {
e.preventDefault(); //If not, prevent the (default) submit behaviour
}
});
The fiddle has been edited to reflect these changes.
You could use if(!$('.question').eq(currentQuestion).find('input').filter(function(){return this.value==""}).length) to check if there are empty fields. Fiddle: http://jsfiddle.net/ilpo/cuqerfxr/1/
$('.question') selects all the questions
.eq(currentQuestion) selects the question you're currently at
.find('input') selects all the input fields inside the current question
.filter(function(){return this.value==""}) selects only empty input fields
.length counts the amount of matches, e.g. amount of empty inputs
if(number) returns true with a positive value, e.g. if there were any empty inputs
! in front of it all inverts it, returning true if there are no empty fields
Related
I have a form with a series of radio items. If a user chooses a specific entry on one of the radio items (missing item) I use JQuery to add a bootstrap is-invalid class to two specific inputs on the form along with a label asking them to add detail and disable the submit button to stop them submitting the form.
$(function () {
$("input[name=optradio]:radio").click(function () {
if ($('input[name=optradio]:checked').val() == "2") {
$('textarea[name=sentTo]').addClass('is-invalid');
$('input[name=dateSent]').addClass('is-invalid');
$('#removedMSG').text("You must update this field prior to saving");
$('#removedMSG2').text("You must update this field prior to saving");
$('#submit').prop('disabled', true);
} else {
$('textarea[name=sentTo]').removeClass('is-invalid');
$('input[name=dateSent]').removeClass('is-invalid');
$('#submit').prop('disabled', false);
}
});
});
I would like to add further checks to make sure the user updates the two inputs (ones a textarea) before I re-enable the submit button.
I know I can use the following to check for input changes
$("textarea[name=sentTo]").on("input", function(){
$('textarea[name=sentTo]').removeClass('is-invalid');
});
This works fine. However I am at a loss how to integrate it all together:
So basically user selects the radio, is-invalid gets added to 2 input fields and the submit button disabled - user completes 2 fields as required and only when both fields have been updated do we then re-enable the submit button.
I am thinking I need an if statement but I can't seem to get the code right.
I tried
if `$("textarea[name=sentTo]").on("input") && $("textarea[name=dateSent]").on("input")`
but this doesnt work
Thanks to Mamum I am using the code below.
$(function () {
$('input[name=optradio]:radio').click(function () {
if ($('input[name=optradio]:checked').val() == "2") {
$('textarea[name=sentTo]').addClass('is-invalid');
$('input[name=dateSent]').addClass('is-invalid');
$('#removedMSG').text("You must update this field prior to saving");
$('#removedMSG2').text("You must update this field prior to saving");
$('#submit').prop('disabled', true);
$('#submit').addClass('btn-danger');
$('#submit').removeClass('btn-primary');
} else {
$('textarea[name=sentTo]').removeClass('is-invalid');
$('input[name=dateSent]').removeClass('is-invalid');
$('#submit').prop('disabled', false);
$('#submit').addClass('btn-primary');
$('#submit').removeClass('btn-danger');
}
});
});
var sentTo = false;
var dateSent = false;
$("textarea[name=sentTo], input[name=dateSent]").on("input", function(){
if($(this).attr('name') == 'sentTo') {
sentTo = true;
$(this).removeClass('is-invalid');
}
if($(this).attr('name') == 'dateSent') {
dateSent = true;
$(this).removeClass('is-invalid');
}
if(sentTo && dateSent){
$('#submit').prop('disabled', false);
$('#submit').addClass('btn-primary');
$('#submit').removeClass('btn-danger');
}
});
You can pass multiple selector separated by comma and use this keyword to refer the current element inside the event handler function:
var sentTo = dateSent = false;
$("textarea[name=sentTo], textarea[name=dateSent]").on("input", function(){
if($(this).attr('name') == 'sentTo') sentTo = true; //true for sentTo
if($(this).attr('name') == 'dateSent') dateSent = true;//true for dateSent
if(sentTo && dateSent){ // if both are true
$(this).removeClass('is-invalid');
sentTo = dateSent = false;
}
});
I am trying to focus the first empty input element on first submit but when the email and password inputs are empty, it always focuses on the password (latter) input first.
How can I focus on the first empty input in a way that works across all browsers?
$('input').each(function() {
if ($(this).val() == '') {
this.focus();
}
});
This happens because you are iterating over all input elements and calling .focus() if it has no value. If both the username field and the password field have no value, it will first call .focus() on the username field, but then it will continue iterating and call .focus() on the password field too, which takes focus away from the username field. What you want is to stop iterating over the input fields when you detect the first one with no value. To do this just return false; to tell JQuery's each to stop iterating.
$('input').each(function(){
if($(this).val() == ''){
this.focus();
return false;
}
});
For comparison, see this demo:
Your way: http://codepen.io/Chevex/pen/XbpeMd
With return false;: http://codepen.io/Chevex/pen/VLPMpr
You can see your bug is reproduced in the first demo, and then it's fixed in the second demo. You can load those demos in any browser and see that it works.
Edit: Here it is working in Opera.
Here it is in vanilla JavaScript:
var input = document.getElementsByTagName('INPUT');
for (var i = 0, n = input.length; i < n; i = i + 1) {
// may also need to test for input[i].type
if (!input[i].value) {
input[i].focus();
break;
}
}
Just return false; after you focus the element to break the $.each() loop. Currently the focus will be set to your last empty element as the loop continues.
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
Source: https://api.jquery.com/jquery.each/
Edit, to be clear:
$('input').each(function() {
if ($(this).val() == '') {
this.focus();
return false;
}
});
Edit, so you won't have to read all the comments:
The complete solution was to use event.preventDefault() in the according onSubmit handler and then check the inputs for empty values in it.
Afterwards some further processing (as in: validating and finally submitting it to the (server-side) application) of the inputs is needed of course.
$('#loginForm').on('submit',function (e) {
e.preventDefault();
// focus first empty input
$('#loginForm input').each(function() {
if ($(this).val() == '') {
this.focus();
return false;
}
});
// further input processing
});
I have a form in which I have hidden some inputs when a button is clicked. I have a validation code, which runs through every input and prints an error message if there are empty inputs. But in order to submit the form I have to fill every element, including the invisible ones, because the code is printing the message although I have filled all visible elements.
Here is the code for the validation
$('button.submit-first').click(function() {
var emptyElements = $('form.registration-form div.first-part :input').filter( function() {
return this.value === '';
});
if (emptyElements.length === 0)
{
$('p.red').css('display', 'none');
}
else
{
$('p.red').css('display', 'block');
$('html, body').animate({scrollTop: $('div.row').offset().top}, 800);
}
});
I can't seem to figure out how should I go through the inputs and if there are invisible ones just skip them and check the visible ones.
You can just add ":visible" to the input to only validate those.
$('button.submit-first').click(function() {
var emptyElements = $('form.registration-form div.first-part :input:visible').filter( function() {
return this.value === '';
});
I need to take text from fields which have the same class. But when I apply the condition that if field is empty, give an alert, it checks the condition for the first time and ignores all the others as fields are all on the same page with the same class. I cannot have unique classes for every field because the divs are dynamically generated.
Here's my code,
$(document).on('click', '.submit-button', function(){
var maintain=$('form input.inputs-field').val ();
if(maintain == ''){
alert('Please fill that field');
return false;
}
else{
$(document).trigger('save-single-answer', {
answer: $(this).siblings('.inputs-field').val()
});
return true;
}
});
Use .each() to check all the fields. Current you just get the value of first matched element in maintain.
$(document).on('click', '.submit-button', function () {
var maintain = $(this).siblings('.inputs-field').val(); //OR $(this).val()
if (maintain == '') {
alert('Please fill that field');
return false;
} else {
$(document).trigger('save-single-answer', {
//here I assume `this` meant button before (in your code)
answer: maintain
});
return true;
}
});
I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY