Checking my users input is a number of a set length? - javascript

Ok, I have a form with lots of different inputs, each has the same class name on it. What I need to do is loop though all of these inputs, which the user can add more to, with an AJAX call, making sure all inputs are four numbers only.
Now I can get it to check that it is of a length but when I try to add a check to make sure its a number, it does not seem to work, this is my current code:
var ValidMyData = function() {
$('#FORM-ID-HERE').on('submit',function(e) {
e.preventDefault();
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
$(Numbers).each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 ) {
return $(this).css("background-color","#FF0004");
} else {
return $(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
This works, if the inputs on my number field are not four in length, it makes the background color red, and then removes that background color if its then changed to be four.
I have tried some things but nothing as worked. I have mainly being playing with the IsNumeric() function, by adding that on my if check. Also, although this works, I don't think my return call is working right, I think I am doing something wrong but can not put my finger on it :). - When I console.log the CheckNumbers() inner function, I get undefined back.
All help most welcome.
Thanks

this code will check if it is 4 characters and if it's a number:
var ValidMyData = function() {
$('#FORM-ID-HERE').bind('submit',function(e) {
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
Numbers.each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 || !/([0-9])+/.test(String(GetCurrentInput))) {
return $(this).css("background-color","#FF0004");
e.preventDefault();
} else {
$(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
EDIT
I updated the answer using your own code, which now will submit the form if all the inputs are filled correctly, else it highlights it and doesn't submit the form.

Related

Form calculator based on input values

I am working on a Cardio Test calculator which calculates heart attack risk. I want to get score based value for each input. The results logic is already working, I just need to get result score value. See the code below.
<script>
$(document).ready(function() {
$("#female").change(function() {
if ($(this).is(":checked")) {
$("#femaleage").show();
$("#maleage").hide();
}
});
$("#male").change(function() {
if ($(this).is(":checked")) {
$("#maleage").show();
$("#femaleage").hide();
}
});
$( "#cardio__test" ).submit(function( event ) {
event.preventDefault();
if ($("#score").val() <= 3) {
$(".risk__score.low__risk").show();
}
if ($("#score").val() >= 4 && $("#score").val() <= 6) {
$(".risk__score.moderate__risk").show();
}
if ($("#score").val() >= 7) {
$(".risk__score.high__risk").show();
}
if ($("#maleage").val() >= 70) {
$("#score").val() + 8;
}
$(this).hide();
});
});
</script>
Here's a link!
I tested out your codepen and I found out the value of your score is a string type instead of int as I tested using parseInt() and typeof... and the result string value is blank (maybe i changed some code in the codepen during testing) How do you check the value of the score and do you get it as a number? Anyway, to print out the result value you can do it in many ways such as
adding a new div in your results div and print the results inside the div
$(".(new div class name) h3").text($("#score").val());
or simply alert the results
alert($("#score").val());
you can simply use
var scoreValue = $("#score").val();

detailed conditional submit preventDefault

I've spent some time looking around and trying multiple solutions without luck, while attempting to streamline a form to create a pseudo bulk process.
Essentially I simply need to prevent default on a submit button, but to trigger it if several subconditions are met, at least one of which uses an ajax call.
I've tried variations of e.preventDefault, $('#form').submit(false); and I can either get the validation to occur, or the form to submit, but never both in the right places. (for example it will submit without checking for duplicate entries)
Here's a summed up version of what I've been attempting.
This is the main variable which holds the first part of the check:
var verifyValue = function() {
// this stops the form, and then things validate fine.
$('#add-item-form').submit(false);
//but then I need to get it started again to submit valid entries
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
jQuery.getJSON('{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()}))
.done(checkedValue);
}
};
This is where it is called:
$("#verify-value").click(verifyValue);
Below is a shorthand of the conditional being run:
var checkedValue = function(items) {
if(items.length == 0){
// success conditions
}
else {
//this was just one attempt
$('#form').submit(false);
if( /* sub condition of data passed from JSON array */){
//condition creates new form which upon action sends AJAX call
}
else
{
//second error condition
}
}
};
What I'm trying to do is to have if any of the subconditions occur, to have it stop the submit button (e.g. preventDefault behavior) and if it does not have any of these, to allow the submission of the form
It feels like it should be simple, however no matter where I do this, including using $(this).unbind('submit').submit() It doesn't work right.
Either the validation occurs correctly and nothing submits, or everything submits even if it's not supposed to.
I feel like modifying var verifyValue will work but I'm not sure how to get the conditional statements bound into an event.
Edit:
Okay, so I was guilty of seriously overthinking this issue, and came up with a solution which I will put below (in case anyone is interested)
Since your validation includes an async step, it'd be easier to just stop the form submission right away.
Then call your validation function, which will set the validation state of the form in a "global" state (maybe just a closure of the event handler). If the validation is fine, submit the form, else just show the validation error.
// You'll need to reset this if an input changes
var isFormValid = false;
$("#form").on('submit', function(e) {
if (isFormValid) {
return true;
}
e.preventDefault();
validateForm(function(valid) {
if (valid) {
isFormValid = true;
$('#form').submit();
}
});
});
function validateForm(cb) {
var form = $('#form');
// do some synchronous validations on the form inputs.
// then do the async validation
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
jQuery
.getJSON(
'{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()})
)
.done(function(result) {
if (checkedValue(result)) {
cb(true);
} else {
cb(false);
}
});
} else {
cb(false);
}
}
How about this approach, here's a simple skeleton:
$('#form').submit(function(e){
var formError = false;
// set formError to true if any of the checks are not met.
if(some condition) {
// do a conditional check
formError = true;
} else if(another condition) {
// do another conditional check
formError = true;
}
if(formError) { // stop form submission of any of the conditions are not met.
return false; // same as e.preventDefault and e.stopPropagate()
}
});
It turned out I was seriously overthinking this issue. It was a lot easier to handle by binding everything into a button that was not a submit, and if it passed the validation simply use a submit condition. This way I didn't need to worry about preventing default behavior and turning it back on again (which was where I was getting stuck). Since regular buttons have no default behavior, there was no need to be concerned about it submitting incorrectly.
The original function just needed to be simplified to:
var verifyValue = function() {
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
$('#barcode-buttons').hide();
jQuery.getJSON('{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()}))
.done(checkedValue);
}
};
$("#verify-value").click(verifyValue);
and then the check only needed to do this
var checkedValue = function(items) {
if(items.length == 0){
$('#form').submit()
}
else {
//error conditions
}
};

Preventing next tab if current tab have empty field

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

Enabled and Disabled submit button when multiple fields are empty isn't working

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

jQuery if (x == y) not working

So, I have some faux checkboxes (so I could style them) that work with jQuery to act as checked or not checked. There are a number of faux checkboxes in my document, and for each one I have a click function:
var productInterest = [];
productInterest[0] = false;
productInterest[1] = false;
productInterest[2] = false;
// here is one function of the three:
$('#productOne').click(function() {
if (productInterest[0] == false) {
$(this).addClass("checkboxChecked");
productInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
productInterest[0] = false;
}
});
The problem seems to be that there is an error in the if statement, because it will check, but not uncheck. In other words it will add the class, but the variable won't change so it still thinks its checked. Anybody have any ideas? Thanks for your help.
UPDATE: So, I need to show you all my code because it works in the way I supplied it (thanks commenters for helping me realize that)... just not in the way its actually being used on my site. so below please find the code in its entirety.
Everything needs to happen in one function, because the UI and data for each checkbox need to be updated at once. So here is the complete function:
$('input[name=silkInterest]').click(function() { // they all have the same name
var silkInterest = [];
silkInterest[0] = false;
silkInterest[1] = false;
silkInterest[2] = false;
if ($(this).is('#silkSilk')) { // function stops working because the .is()
if (silkInterest[0] == false) {
$(this).addClass("checkboxChecked");
silkInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[0] = false;
}
alert(silkInterest[0]);
}
if ($(this).is('#silkAlmond')) {
if (silkInterest[1] == false) {
$(this).addClass("checkboxChecked");
silkInterest[1] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[1] = false;
}
}
if ($(this).is('#silkCoconut')) {
if (silkInterest[2] == false) {
$(this).addClass("checkboxChecked");
silkInterest[2] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[2] = false;
}
}
var silkInterestString = silkInterest.toString();
$('input[name=silkInterestAnswer]').val(silkInterestString);
// This last bit puts the code into a hidden field so I can capture it with php.
});
I can't spot the problem in your code, but you can simply use the class you're adding in place of the productInterest array. This lets you condense the code down to a single:
// Condense productOne, productTwo, etc...
$('[id^="product"]').click(function() {
// Condense addClass, removeClass
$(this).toggleClass('checkboxChecked');
});
And to check if one of them is checked:
if ($('#productOne').hasClass('checkboxChecked')) {...}
This'll make sure the UI is always synced to the "data", so if there's other code that's interfering you'll be able to spot it.
Okay, just had a palm to forehead moment. In regards to my revised code- the variables get reset everytime I click. That was the problem. Duh.

Categories

Resources