Validate all or none text fields in Kendo & dynamically remove messages - javascript

For the code below it looks for an empty field in the 4 required fields if the user enters the address/city/state/zip field. Then it loops to check if any of them are empty. If all 4 are empty, then validation passes. If All of them contain data, then it should pass. The only time it should fail is if 1-3 of them are empty.
var validator = $("#AddressInfoForm").kendoValidator(
{
rules: {
PayeeRequired: function (input) {
if (input.is("[name=Address]") || input.is("[name=City]") || input.is("[name=State]") || input.is("[name=Zip]")) {
var fieldsBlank = 0;
var requiredFields = ["Address", "City", "State", "Zip"];
for (var i = 0; i < requiredFields.length; i++) {
var val = $('#' + requiredFields[i]);
if (val.val() == "") {
fieldsBlank += 1;
}
}
if (fieldsBlank > 0 && fieldsBlank < 4 && input.val() == "")
input.addClass("inputfields-validation-error");
fieldsBlank = 0;
return false;
}
input.removeClass("inputfields-validation-error");
return true;
}
}
},
}
).data("kendoValidator");
The issue I'm having with this is that...
The previous validation messages do not disappear. They only disappear once I click into each input box. It should be checking dynamically across the board since all 4 fields are linked. This means if 3 fields are empty except one, then there should be errors for those 3 fields. Once I clear the 4th field, then all of those errors should hide. Unfortunately it only hides for the last field that I input into and then I need to individually click into each field.
Working code expectant...
Overall I am looking for improve/correct my code so that
Show the error message for the blank fields when more than zero and less than 4 are blank.
Dynamically update so that when I clear all the fields, it clears all the error messages. When I fill one, then the other 3 blank fields display errors.
No errors when all 4 are filled.
edit--------
utilizing
$("#Address, #City, #State, #Zip").on("change", function () {
isModified = true;
validator.validate();
});
Seems to work how I want; however, validator.validate() sets off the validation errors for all the other fields in my form. I only want the validation set off for the 4 fields Address, City, State, and Zip. Any ideas?

$("#Address, #City, #State, #Zip").on("change", function () {
validator.validateInput($("input[name=Address]"));
validator.validateInput($("input[name=City]"));
validator.validateInput($("input[name=State]"));
validator.validateInput($("input[name=Zip]"));
});
Seems to work well. Let me know if there's a better way to do this!

Related

Cursor jumps from input to input when .reportValidity() is being assessed as a variable

I am checking the validity of five unique inputs to prevent form submission when invalid inputs remain.
sE.addEventListener("input", (e) => {
if (
Number.isNaN(e.target.valueAsNumber) ||
sE.valueAsNumber >= Number(sE.max) ||
sE.valueAsNumber <= Number(sE.min)
) {
e.preventDefault();
calcButton.disabled = true;
} else {
calcButton.disabled = false;
}
This does appear to work to prevent the calculation button from being enabled, but only when the input (ie sE) is being looked at. This doesn't look at all the other inputs.
So I thought it would be better to try this:
sE.addEventListener("input", (e) => {
let reportS = sE.reportValidity();
let reportU = uE.reportValidity();
let reportV = vE.reportValidity();
let reportA = aE.reportValidity();
let reportT = tE.reportValidity();
console.log(reportS, reportU, reportV, reportA, reportT);
if (
Number.isNaN(e.target.valueAsNumber) ||
sE.valueAsNumber >= Number(sE.max) ||
sE.valueAsNumber <= Number(sE.min)
) {
e.preventDefault();
calcButton.disabled = true;
} else {
calcButton.disabled = false;
}
});
This gives me the appropriate true/false relationship between all five inputs. But, when you click on one of the inputs on the HTML form and enter a number, the cursor then jumps to the last selected input. This makes input impossible.
When I removed the let statements and put them outside of the function they do not call the correct true/false relationship as they aren't updated as each input has new data added. However, when the let statements are outside of the function, even though they do not accurately reflect the true/false relationship, the cursor does not jump from input to input.
I am very much a beginner so I am not sure what to look for when it comes to troubleshooting this strange phenomenon.
I made a JSBin for this https://jsbin.com/gowulec/edit?html,js,output
When you click all three checkboxes and then try to add data into the input.

JavaScript real time validation and calculations 2 or more input text fields

I want to do JavaScript real time calculations oninput, without the need for a submit button.
I know how to do real time calculations in JavaScript when I have 1 input text field. I use the oninput event for the input text field.
But what about when I have 2 text fields?
I want it to do something like this link, where it validates and calculates without the need for a submit button:
https://www.easycalculation.com/algebra/modulo-calculator.php
Take the following code for example:
// input
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
// calculation
var result = a * b;
// display result
document.getElementById("result").value;
Since there are 2 input text fields (a and b), I want it to do the instant/real time calculations only AFTER the user has inputted valid data in BOTH text fields.
But I also want it to do real time calculations if the user changes either field. So if they input "a" and "b" it gives the results, but if they change "a" then it immediately gives new results without them having to touch "b" at all.
How do you suggest I go about doing this? Because I dont want the answer to keep showing up as Zero right after typing in the first text field. I want it to wait until both fields have numbers inputted and validated before it starts real time calculation. I will be adding validating code to this as well.
thanks
Just try and formulate your problem so that the computer can understand it.
I'll do just some pseudo-code. So you want to calculate something:
function calculate (valueA, valueB) {
... do something ...
... output result ...
}
You want to check, if both fields are valid, and only then do the calculation and output:
function checkFields (fieldA, fieldB) {
if (fieldA.value.length > 0) { // if it is empty, there is no input
... do some additional checking ...
if (fieldB.value.length > 0) { // if it is empty, there is no input
... do some additional checking ...
... if all went well: calculate (fieldA.value, fieldB.value);
}
}
}
then bind your checkFields to both input fields, and the computer understands.
you should write a function like validate() where you have to check the value of both the inpute fields if its valid then calculate result otherwise show a warning message above the field which is either empty or having wrong value
You have to call the validate function on onchange event of both the inputs
This is not exactly how I would write this in a production evvironment. but this should at least give you a good start for what you are looking for - very basic functionality you described.
<form>
<input id='a' class='ab' type='text' name='valA'>
<input id='b' class= 'ab' type='text' name='valB'>
</form>
// JS code below with this markup
var someCompositeGroup = document.getElementsByClassName("ab");
function validateForm(){
// add stuff here
var inputVal = 0;
var aVal = someCompositeGroup[0] && someCompositeGroup[0].value;
var bVal = someCompositeGroup[1] && someCompositeGroup[1].value;
if (aVal && bVal && !isNaN(aVal) && !isNaN(bVal)) {
inputVal = aVal * bVal;
// only update here -
console.log(inputVal);
} else {
console.log(' not ready to calculate yet ');
}
}
for (var i = 0; i < someCompositeGroup.length; i++) {
someCompositeGroup[i].addEventListener('keyup', validateForm);
}

Disable textbox based on input entered

I have 7 input textboxes.Based on the input enter i need to disable them accordingly.For eg if i enter input as 4 out the first four text boxes should be diabled accordingly(input is restricted to less than 7),and this is to be done using Jquery
This is a simple example on how to do that:
$("input").on("change", function()
{
$("input:lt(" + $(this).data("index") + ")").prop("disabled", "disabled");
});
Fiddle.
Using data attributes I set the index of each element(you can use index() in some cases, but it is more complex). So, when any element is changed I get all inputs with index less than the changed one (input:lt(index)) and disable it setting its property disabled.
I hope it is clear.
for (i = 0; i < contract; i++)
{
$('#tblTest').find('tbody').find('tr').find('.Year')[i].disabled = false;
var samtes = $('#tblTest').find('tbody').find('tr').find('.Year')[0].disabled = false;
}

Limiting the number of checkboxes selected by user

i have a page on there.i have number of check boxes.i want user to select on three not more than that and one check box has the value "NOT interested ",if user click on this all other check box must has to disabled.for that i tried javascript.
this is what i tried
function chkcontrol(j) {
var total = 0;
for (var i = 0; i < document.form1.user[portal_choice].length; i++) {
if (document.form1.user[portal_choice][i].checked) {
total = total + 1;
}
if (total > 3) {
alert("Please Select only three")
document.form1.user[portal_choice][j].checked = false;
return false;
}
}
}
i getting error in the portal_choice variable.That is mapped with the database column name and user is my table name.
help me to do that and suggest me to disabling the checkbox when user click on "NOT INTERSTED".and its not rail 3.0
thanks pal for consideration.........
Using this syntax document.form1.user[portal_choice], you are telling Javascript that you want the form called 'form1' and from that form, get the elements called 'user', and look at the one with an index that is contained in the (javascript) variable 'portal_choice'. That variable is not defined in your function.
I am not familiar with Ruby, but from some quick reading, it looks like you can refer to Ruby variables directly in html, but not in Javascript. I think you have to wrap it with <%= %> like so:
document.form1.user[<%= portal_choice %>].length
However, I don't see why you would use a Ruby variable here. You just want to iterate through all of the checkboxes, right? I don't think checkbox elements are ever 2-dimensional arrays, as in
document.form1.user[portal_choice][i]
I think you really just want to do this:
function chkcontrol(j) {
var total = 0;
for (var i = 0; i < document.form1.user.length; i++) {
if (document.form1.user[i].checked) {
total = total + 1;
}
if (total > 3) {
alert("Please Select only three")
document.form1.user[j].checked = false;
return false;
}
}
}
Check this fiddle

How do I pass form elements to a javascript validation function?

I have a form that lists users, and for each user there is a drop down menu (2 choices: waiting, finished) and a comments textbox. The drop down menus are each labeled "status-userid" and the comments textbox is labeled "comments-userid" ... so for user 92, the fields in his row are labeled status-92 and comments-92.
I need to validate the form in the following way:
If the value of the status is "finished", I have to make sure that the user entered comments to correspond with that specific drop down menu.
So far, I have:
function validate_form () {
valid = true;
/*here's where i need to loop through all form elements */
if ( document.demerits.status-92.value == "finished" &&
document.demerits.comments-92.value == "")
{
alert ( "Comments are required!" );
valid = false;
}
return valid;
}
How do I loop through all of the status-userid elements in the form array?! Or is there another way to do this?
This should do it in raw Javascript (no framework).
var form = document.demerits;
for (var i = 1; i <= 100; i++)
{
if (form["status-" + i.toString()].value == "finished" &&
form["comments-" + i.toString()].value == "")
{
// enable visibility of element next to comments indicating validation problem
valid = false;
}
}
Using alerts would be bad though.
You'll need a collection of the dropdowns in your form. This can be acquired by using getElementsByTagName.
var dropdowns = document.demerits.getElementsByTagName("select");
for (var i = 0; i < dropdowns.length; i++)
{
// You can now reference the individual dropdown with dropdowns[i]
}

Categories