JavaScript -- Validating a Certain Number of Inputs - javascript

I have 8 form inputs that are asking for either 8 half-day activity dates or, 4 fullday dates.
I collected all of the input values and put them into an array, and to test the collection process, wrote the following function that just says if ALL the inputs are empty, keep a button disabled and if ALL are full, enable the button.
function checkMeetings()
{
for(var i = 0; i < meetings.length; i++)
{
if(meetings[i] === "" || meetings[i] === null)
{
meetingsCanSubmit = false;
}
else
{
meetingsCanSubmit = true;
}
}
}
checkMeetings();
That test worked fine.
What I'd like to do is create a counter that counts the number of input boxes that have been filled in and when it gets to at >= 4 enable the button. (In reality it won't enable the button it's going to run a secondary function but for the purposes of this example I'm keeping it simple.)
Since the for loop is counting via the i++ anyways, I tried something to the effect of
if(meetings[i] <= 4) do the following, but that doesn't seem to be doing the trick. Should I be setting up a second counter within my if-statement?

You can use Array.prototype.filter(), check the .length of resulting array
var meetingsCanSubmit = meetings.filter(function(input) {
return input !== "" && input != null
}).length >= 4;
if (meetingsCanSubmit) {
// do stuff
}

Related

GridView Validation is not working properly in JavaScript

I want to validate on button click that at least one of the rows must be edited and updated in JavaScript.
So I wrote the below code for validation
function checkGridValidate() {
var StrPriError = "";
var grdCount = GrdProspective1.Rows.length;
for (var i = 0; i < grdCount; i++) {
if (GrdProspective1.Rows[0].Cells[5].Value == "" || GrdProspective1.Rows[0].Cells[7].Value == "") {
StrPriError += "Kindly edit atleast one row \n";
}
if (StrPriError != "") {
alert(StrPriError);
return false;
}
else {
return true;
}
}
}
What happening here is, when I update the first row and submit it is not giving any alert that's perfect, but when I update the second row it still asks me Kindly edit at least one row.
I don't know what's going wrong here.
Have a look the js fiddle for the same
Currently, the validation is limited to only check the top row for two reasons:
.Rows[0] will always inspect the top row, despite the for loop.
This should make use of i as it increments through the collection:
if (GrdProspective1.Rows[i].Cells[5].Value == "" ||
The last if..else, by returning in either case, will interrupt the loop. The return statements here have a similar effect to break statements, with regards to the loop.
So, unless you want the loop to be interrupted, they should be moved out the loop:
for (var i = 0; i < grdCount; i++) {
if (...) {
// ...
}
}
if (StrPriError != "") {
alert(StrPriError);
return false;
}
else {
return true;
}
Though, fixing those should reveal a different issue – the function is checking that every row has been edited rather than one-or-more.
If, for example, there are 5 rows and you fill in both fields in 2 of the rows, the remaining 3 rows will match the condition and append the error message.
Inverting the condition, so you're searching for a row that's filled in and remembering whether you have, should resolve this.
function checkGridValidate() {
// assume invalid until found otherwise
var anyEdited = false;
var grdCount = GrdProspective1.Rows.length;
for (var i = 0; i < grdCount; i++) {
var cells = GrdProspective1.Rows[i].Cells;
// verify that both fields were given a value
if (cells[5].Value !== "" && cells[7].Value !== "") {
anyEdited = true; // remember that you've found an edited row
break; // and, no need to keep looking for more
}
}
// alert only if no rows were filled out
if (!anyEdited) {
alert("Kindly edit at least one row.");
}
return anyEdited;
}

How to use JavaScript to Require a Ratio of Completed Fields in a Form

I'm looking for a way to use JavaScript to require a specific ratio of fields in a form to be complete. So if I have six fields and the user has to complete any 2/6 to submit. If not then they receive an error. (The form will actually have a few different groups like this in it, so I have to be able to identify specific fields for the ratio.)
After some more research I've found something close, and realize I can count the number of a class. How would I change this to say if number of checked boxes is greater than or equal to 2, return true?
document.getElementById("test").onclick = function() {
isCountCheck("Check something");
};
function isCountCheck(helperMsg) {
var i, len, inputs = document.form1.getElementsByClassName("checkbox");
for (i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) return true;
}
alert(helperMsg);
return false;
}
UPDATE:
My final jQuery ended up like this.
function isCountCheck(){
if($("input[class=crit1]:checked").length >= 4)
return false;
alert("Check a box");
return true;
}
Using jQuery
var numberOfInputsCompleted = 0;
var allInputs = $(":input"); // returns all input fields on the document
var numberOfInputs = allInputs.length
allInputs.each(function () {
if($(this).val() != '') {
numberOfInputsCompleted = numberOfInputsCompleted + 1;
}
});
numberOfInputsCompleted would give fields completed and numberOfInputs would total number of input fields on the form. Hope this helps
The first thing that comes to my mind: create a function that counts filled fields and returns true if the number of filled fields is enough (false otherwise). Then add it to the form as an "onsubmit" function. When the submit button is clicked the function is executed and, depending on what the function returns (true or false), the form is submitted or not.
More info about javascript form validation: http://www.w3schools.com/js/js_form_validation.asp

Iterate through all but one elements in a form

I would love my while to iterate through all but one of the elements in the form. This is my code:
while (i < elnum && !empty) {
if (form.elements[i].value == "" && form.elements[i] != form.referral) {
error.innerHTML += 'All fields are required.</br>';
empty = true;
}
i++;
}
Where elnum is the number of elements.
Unfortunately, even if I leave only form.referral empty, it still enters inside the if. Basically, I want the check to be done for all fields but for that one.
Rather than trying to compare elements, try something like this:
if( form.elements[i].name == "referral") continue;
Put that just inside the loop, before the condition to check for an empty value.
That being said, it might be better to do something like this:
while(i < elnum) {
if( form.elements[i].hasAttribute("required") && form.elements[i].value == "") {
error.innerHTML += "All fields are required.<br />";
// re-add `empty=true` if the variable is needed elsewhere
// if it's only used to end the loop, then this is better:
break;
}
i++;
}
And make sure you add the required attribute to all required fields. This is a better solution because then it will take advantage of the browser's native ability to handle HTML5 forms, if it has any.

jQuery check that at least five inputs have data in them

I have a number of inputs on the page and need to force that at least 5 items have been filled. And if not then show a message saying you must fill at least 5. So far I have tried the following but it just shows the error over and over again. What's the proper way of doing this?
$('div.inputs input').each(function(i) {
$input = $(this);
while (i < 5) {
if ($($input).val() == '') {
alert('must fill at least 5 items!');
}
}
});​
You can create a better selector, and then:
if ($('div.inputs input[value!=""]').length < 5) {
alert('must fill at least 5 items!');
}
Explanation:
The div.inputs input[value!=""] selector selects all input fields which has something in the value attribute, and then you can fetch the length of the selected items.
The previous solution works (somehow), but I recommend a better one:
if ($('div.inputs input').filter(function () { return $(this).val().length > 0; }).length < 5) {
alert('must fill at least 5 items!');
}
The methods shown in KARASZI István's answer are neater, but as far as explaining what is wrong with your code and how you might fix it, the (main) problem is that the while condition:
while(i<5)
...is evaluating a variable, i, that is not changed by the contents of the loop. On the first iteration of the .each() loop i is 0 so the while condition is true and remains true so you get an endless loop.
To keep the general structure of your code and loop through each input testing the values you could do something like this:
var filled = 0;
$('div.inputs input').each(function (i) {
if (this.value != '') {
filled++;
if (filled === 5)
return false;
}
});
if (filled < 5) {
alert('must fill at least 5 items!');
}
That is, for each input that is not blank increment a counter, and then check the counter after the loop. Note that returning false from within the .each() callback function stops the .each() loop immediately; no need to keep counting once we've reached the minimum 5 non-empty values.

Strange results with javascript array.length function

I have piece of JavaScript code which cycles through form elements and builds an object.
I have a mixture of HTML input fields and ASP.NET input fields. ASP.NET changes the ID of the fields to the form xxxxx_yyyy_id, so I am attempting to use the split function to extract the original id.
// Iterate over all the text fields and build an object
$(':text').each(function () {
var tokens = this.id.split("_");
if (tokens.length = 3) {
// Assume this is a .net inputbox - extract the original id
inFormData[tokens[2]] = this.value;
} else {
inFormData[this.id] = this.value;
}
});
Stepping through the above code, the first id is ctl00_ContentPlaceHolderCol1_forenameField, so the tokens.length = 3 code is run.
On the second iteration, the id is forenameField2 so I would expect the tokens.length to be 1, but it is actually 3. The else statement is never run.
This could be something simple, but I cant work it out. If I inspect the tokens array it has only 1 element in on the second iteration. I have also tried setting the array.length to 0 after each iteration.
Any help appreciated.
Correct this:
== instead of =. === is more better
if (tokens.length == 3) {
// Assume this is a .net inputbox - extract the original id
inFormData[tokens[2]] = this.value;
} else {
inFormData[this.id] = this.value;
}
Change your = 3 to === 3
At the moment you're overwriting tokens.length every time.
NB: === is preferred to == because it's an exact equality check. The two-equals version will attempt to cast the two operands to the same type before comparison, which is 1. unnecessary, 2. inefficient, 3. sometimes error prone.
That is why you should always put the constant first when testing. If you forget a comparison sign it will throw an error:
if( 3 = tokens.length ) // throws an error
if( 3 == tokens.length ) // ok
if( 3 === tokens.length) // ok
from:
if (tokens.length = 3) {
to:
if (tokens.length == 3) {

Categories