jQuery empty input check function not working as expected - javascript

This question has been done to death on SO and I'm really, really sorry! I've already taken the bones of the below idea from a couple of SO questions on the same theme.
All said though, I still can't get it to work as expected.
It works OK if NONE are filled in.
It works OK if the END input is filled in and not the others.
It works OK if the MIDDLE input is filled in.
If you fill in ONLY the FIRST input though, it alerts, but submits anyway?
JSFIDDLE
$(document).ready(function (e) {
// completed count submit handler
$("#submit_counts_button").on('click', function () {
window.incomplete = false;
$('input[type=number]').each(function () {
if ($(this).val().length == 0) {
window.incomplete = true;
alert('Some fields are empty');
return false;
} else {
if (window.incomplete === false) {
$("#submit_counts_button").prop('disabled', true);
$("#submit_counts_button").html('Please Wait ...');
//$("#update_form").submit();
}
}
});
});
});
I'm sure it's something totally embarrassingly obvious but after a 16 hour day, I just can't see it. Any help appreciated ...

You need to pull the 'incompletion' check outside of the .each
$(document).ready(function (e) {
// completed count submit handler
$("#submit_counts_button").on('click', function () {
window.incomplete = false;
$('input[type=number]').each(function () {
if ($(this).val().length == 0) {
window.incomplete = true;
alert('Some fields are empty');
return false;
}
});
if (window.incomplete === false) {
$("#submit_counts_button").prop('disabled', true);
$("#submit_counts_button").html('Please Wait ...');
//$("#update_form").submit();
}
});
});
http://jsfiddle.net/6WpeF/6/

try
if(document.getElementById('id of input').value != ""){}

Related

How could I stop a form submit in this case?

My intention is to check some conditions before submit is done or stop it and show an alert if the results of that condition are false. I need to ask a function localized in another PHP document using POST.
The next case I'm going to show, the alert is showed correctly when "result != 1", but when I test the opposite case "result == 1", the submit doesnt work:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
}
} else {
alert('error');
return false;
}
});
});
I tried in another way, putting event.preventDefault behind every "Return false" but when "result != 1" it shows the alert but do the submit anyways. It happens in every condition (submit doesnt stop).
$('body').on("submit","#formProyecto",function(event) {
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
event.preventDefault();
}
} else {
alert("error");
event.preventDefault();
return false;
}
});
});
As you can see, my goal is to stop the submit if "result != 1" and show an alert or do the submit if all conditions are ok.
Any idea?
Thanks.
The issue you have is that you cannot return anything from an asynchronous function - which your AJAX request is.
To solve this you need to use preventDefault() to stop the form submit event through jQuery, then raise another native submit event if the AJAX request returns a valid result. This second submit event will not be handled by jQuery and will submit the form as you require. Try this:
$(document).on("submit", "#idForm", function(e) {
e.preventDefault();
var form = this;
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result === 1) {
if (functionNameInSameJSPage()) {
form.submit();
}
} else {
alert('error');
}
});
});
This is assuming that functionNameInSameJSPage() is not an async function. If it is then you'll need to use the callback pattern there too.
This is a bit of a tricky one but you can kind of get it to work by doing:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
$('#idForm').trigger("submit.force"); //Trigger submit again but under a different name
}
} else {
alert('error');
}
});
});
$('body').on("submit.force","#idForm", function () { return true; }); //Passthrough
The idea is to retrigger the event but ensure you don't call the same handler.
There's a proof of concept at https://jsfiddle.net/2kbmcpa4/ (there's no actual ajax happening but the promise simulates that, note this example won't work in IE)
Steps to solve the issue :
On actual form submit just block the event and make the rest call.
Based on response again dynamically resubmit by setting the allowSubmit flag.
Because flag is set on second submit, it doesn't prevent the form from submission. Reset the allowSubmit flag.
(function() {
var allowSubmit = false;
$('body').on("submit", "#idForm", function(event) {
var that = this;
if (!allowSubmit) {
event.preventDefault();
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result == 1) {
if (functionNameInSameJSPage()) {
allowSubmit = true; // set the flag so next submit will not go though this flow
that.submit(); // dynamically trigger submit
}
} else {
alert('error');
}
});
} else {
allowSubmit = false; // reset the flag
}
});
})();

jQuery multiple inputs with one Function RegExp

I've got a form with more than 1 inputfields. The format that should be allowed is hh:mm / h:mm. So I already have a function, that checks my input if the format is true inbstandly on input.
So what I want is, if i click on my submit button i'd like to check all the boxes again if the format is right. If true then submit(); else then alert() or something. But that isnt the problmem.
I have no idea how i can realize this. Thank you in advance :))
function validateAbs(inputField) {
var isValid = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])(:[0-5][0-9])?$/.test(inputField.value);
if (isValid) {
inputField.style.backgroundColor = '#bfa';
} else {
inputField.style.backgroundColor = '#fba';
}
return isValid;
}
$(function(){
$('#ist').on('input', function() {
//This is one of ne hh:mm Textboxes
validateAbs(this);
});
});
$(function(){
$('#abssubmit').on('input', function() {
//This is my Submit-Button
});
});
It's surprisingly easy:
$('#abssubmit').on('input', function() {
$("selector-for-the-inputs-you-want-to-check").each(function() {
validateAbs(this);
});
});
If you want to know whether any of them is invalid, you can use filter:
$('#abssubmit').on('input', function() {
var invalidFields = $("selector-for-the-inputs-you-want-to-check").filter(function() {
return !validateAbs(this);
});
if (invalidFields.length) {
// At least one field was invalid
}
});
You will need to change to a submit handler not an 'input' handler:
$('#abssubmit').on('submit', function(ev) {
var isValid;
ev.preventDefault(); // to stop the form from submitting
$('#ist').each(function() {
if (!validateAbs(this)) isValid = false;
});
if (isValid) {
this.submit(); // all the validations succeeded
}
});

Customizing a password strength validator plugin

I am using a plugin called pStrength.jquery.js and for some reason its not submitting the form I have, or it is submitting the form even if it is not supposed to (when I changed the code)
The code i am using is:
$(document).ready(function () {
$('#myForm').submit(function () {
return false;
});
$('#myElement1, #myElement2').pStrength({
'changeBackground': false,
'onPasswordStrengthChanged': function (passwordStrength, strengthPercentage) {
if ($(this).val()) {
$.fn.pStrength('changeBackground', this, passwordStrength);
} else {
$.fn.pStrength('resetStyle', this);
}
$('#' + $(this).data('display')).html('Your password strength is ' + strengthPercentage + '%');
},
'onValidatePassword': function (strengthPercentage) {
$('#' + $(this).data('display')).html(
$('#' + $(this).data('display')).html() + ' Great, now you can continue to change your password!');
$('#myForm').submit(function () {
return true;
});
}
});
});
Someone has told me that I should use booleans and inside the validation checks, set it to true or false.
The problem is that i have no idea how to do this
Is there anyone that could help me and show me the code to do this?
Thank you in advance
The reason it was still submitting was because the onValidatePassword function runs on each individual field, whereas you actually had two fields to validate. If one field validates and the other doesn't, the form would still submit because the Boolean had already been set to true, which was the only condition needed to submit.
Updated code below, you can also refer to the fiddle.
$(document).ready(function () {
$('#myForm').submit(function (event) {
// TODO: check that the two field values match as well
if ($('#myElement1').data('valid') === 'yup' &&
$('#myElement2').data('valid') === 'yup') {
// remove these three lines to make it submit
alert('Submitting...');
event.preventDefault();
return false;
// and uncomment this one line
//return true;
} else {
event.preventDefault();
return false;
}
});
$('#myElement1, #myElement2').data('valid', 'nope');
...
Your complete onValidatePassword callback should now look like this:
'onValidatePassword': function (strengthPercentage) {
$('#' + $(this).data('display')).html(
$('#' + $(this).data('display')).html() + ' Great, now you can continue to change your password!');
formValid = strengthPercentage >= 60;
// set for each element
if (strengthPercentage >= 60) {
$(this).data('valid', 'yup');
} else {
$(this).data('valid', 'nope');
}
}
Inside your onValidatePassword, you're binding to the submit event, instead of submitting the form. Replace this code:
$('#myForm').submit(function () {
return true;
});
with
$('#myForm').submit();

Form validation with Jquery not behaving as expected

I am using jQuery to validate some fields in a form, and seem to be having an issue with one field in particular (#inputTel).
If an incorrect format is entered, an error message pops up underneath, which is fine, but the problem is once the correct format is entered the message does not disappear.
Here's a jsFiddle with the complete demo.
This is the section in question:
//Tel Validate
function is_valid_tel() {
$this = $("#inputTel");
var pattern = new RegExp("^\d{11}$");
if (pattern.test($this.val())) { // valid
if ($this.closest(".control-group").hasClass("error")) $this.closest(".control-group").removeClass("error");
$this.siblings(".help-inline").css("display", "none");
return true;
} else { // error
if (!$this.closest(".control-group").hasClass("error")) $this.closest(".control-group").addClass("error");
$this.siblings(".help-inline").css("display", "block");
return false;
}
}
Every other field works as expected except this one. My jQuery skills are limited so I'm unsure of how to solve this.
Problem in your code:
Replace var pattern = new RegExp("^\d{11}$"); with var pattern = new RegExp(/^\d{11}$/);
Updated code
//Tel Validate
function is_valid_tel() {
$this = $("#inputTel");
var pattern = new RegExp(/^\d{11}$/);// Update this line
if (pattern.test($this.val())) { // valid
if ($this.closest(".control-group").hasClass("error")) $this.closest(".control-group").removeClass("error");
$this.siblings(".help-inline").css("display", "none");
return true;
} else { // error
if (!$this.closest(".control-group").hasClass("error")) $this.closest(".control-group").addClass("error");
$this.siblings(".help-inline").css("display", "block");
return false;
}
}
Check the fiddle http://jsfiddle.net/rfg8H/
You could also use something like below, less cubersome:
$(function() {
function validateTheForm() {
var ok = true;
$(".input-medium").each(function() {
if($(this).val() == "") //use regex actually here
{
$(this).next().css("display","inline");
ok = false;
}
else {
$(this).next().css("display","none");
}
});
return ok;
}
$(".btn").click(function() {
$("form").submit(validateTheForm());
$("form").submit();
});
});

HTML Multi-Page Form Issues (page is refreshing)

I am having a problem with a multi-page form submission. The problem is that the page is refreshing when I press the next page button. I believe it is a return true/false problem, but I don't know where the issue is. Here is the code:
$(document).ready(function () {
var info = [];
function showinfo() {
for (i=0; i<info.length; i++) {
$('#step3 ul').append(
$('<li>' + info[i] + '</li>')
);
};
};
$('#step1_btn').click(function() {
$("input").each(function() {
if (input.type != radio) {
info.push(this.name+':'+this.value);
} else if ($('.radio').is(':checked')) {
info.push(this.name+':'+this.value);
}
});
$('#step1').css('display','none');
$('#step2').css('display','inherit');
$('#progbar').attr('value',33);
return false;
});
$('#step2_btn').click(function() {
$("input").each(function() {
if (input.type != radio) {
info.push(this.name+':'+this.value);
} else if ($('.radio').is(':checked')) {
info.push(this.name+':'+this.value);
}
});
$('#step2').css('display','none');
$('#step3').css('display','inherit');
$('#progbar').attr('value',66);
showinfo();
return false;
});
});
Not sure if that is all you need to see. If you need to see the html as well, I can provide that. Thanks in advance for any help you all can give. I can read javascript fairly well when someone else writes it, but for some reason writing it myself ends up in catastrophe every time.
try event.preventDefault():
$('#step1_btn').click(function(e) {
e.preventDefault();
// your code here
return false;
});

Categories