Select at least one option in HTML - javascript

Situation: I want to create a simple code whereby users must select at least one extension to proceed. Users should select at least 1 or more extension, else an alert message will appear.
Problem: The problem is, if there shall be only 1 extension available for selection, whether it is selected or not, the alert message will appear disallowing the registration to complete.
//Select atleast one extension
var arrCheckboxes = document.checkForm.elements["product"];
var checkCount = 0;
for (var i = 0; i < arrCheckboxes.length; i++) {
checkCount += (arrCheckboxes[i].checked) ? 1 : 0;
}
if (checkCount > 0){
return true;
} else {
alert("Select at least one Extension.");
return false;
}

It is a legacy from the very early days of browsers that if there is only one form control with a name of product, then:
document.checkForm.elements["product"];
will return a reference to that control, not a collection which you seem to expect. Such controls do not have a length property by default so:
arrCheckboxes.length
returns undefined and
i < arrCheckboxes.length
is false so the loop is never entered.
To fix that, use querySelectorAll which always returns a collection:
var arrCheckboxes = document.checkForm.querySelectorAll('[name=product]');
Supported in IE 8+ and everywhere else. A simpler version of your code (assuming it's in the body of a function):
var arrCheckboxes = document.checkForm.querySelectorAll('[name=product]');
for (var i = 0; i < arrCheckboxes.length; i++) {
if (arrCheckboxes[i].checked) return true;
}
alert("Select at least one Extension.");
return false;

Related

JavaScript -- Validating a Certain Number of Inputs

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
}

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;
}

Javascript - check Checkboxes does not work

Recently I tried to get a small javascript to work, which shall only check some checkboxes. The problem is, I have no clue about Javascript and therefore I am a bit lost whilst looking at the google results.
So far I used a syntax checker I have found online which gave no errors (a good sign, but it's not working anyway).
To prevent you from asking, the submitted name of the checkboxes is right (;
This is my code so far, any help would be appreciated and thanks in advance!
function checkAll(name) {
var flag = 0;
//get all checkboxes with that name
var checkboxes = document.getElementsByName(name);
//look if the check all box is checked or not, set the flag
if (document.getElementByName('check_all').checked === true) {
flag = 1;
}
for (var i = 0; i < checkboxes.length; i++) {
//check the boxes or uncheck them
if (flag == 1) {
checkboxes[i].checked = true;
}
else {
checkboxes[i].checked = false;
}
}
}
There's no document.getElementByName function to obtain a single element by name. You'll either need to change that to an ID and use:
if(document.getElementById('check_all').checked === true) {
flag = 1;
}
Or use document.getElementsByName('check_all')[0] in place of document.getElementByName('check_all'). This assumes that there's only a single element on the page with the name check_all, though; if there are multiple you'll want to consider some other way of uniquely identifying them (such as IDs).

How can i know its valid in JS?

I am developing an Adobe interactive form with LiveCycle LC designer with JavaScript.
// Identify required fields (it may be a free text field, drop-down, check box, i mean there 3 kinds possibilties) and make yellow colored them
var myArrayYellow = new Array();
var yellowFields;
yellowFields = my_required_fields_list_string.rawValue
myArrayYellow = yellowFields.split(" ");
for (var i = 0; i < myArrayYellow.length; i++) {
===> Here at this point, i want to check the existence of [i] field in the form that its a valid field/objetc or not? bcz, i have chances of getting non-existing fields in the my_required_fields_list_string, hence prior to assigning yellow color to them, i want to check their validity on the form or not? Pls. let me know the JS for this // if its true/found, then only assign yellow color as below
xfa.resolveNode("MY_ADOBE_FORM.." + myArrayYellow [i]).ui.oneOfChild.border.fill.color.value = "255,255,254"
};
For some other purpose, some expert gave me a JS as below, i tried to tune it as per my above requirement, but its not working
function findNodes(vNode){
if (vNode.className === "field"){
if (vNode.isPropertySpecified("name") === true){
var myStateName = new RegExp(vNode.name);
var returnValue = GFL.search(myStateName);
if (returnValue != -1) {
this.ui.oneOfChild.border.fill.color.value = "192,192,192";
this.access = "readOnly";
} else {
this.ui.oneOfChild.border.fill.color.value = "255,255,255"; //whatever colour is open access
this.access = "open";
}
}
}
for (var a=0;a<vNode.nodes.length;a++) {
findNodes(vNode.nodes.item(a));
}
}
findNodes(xfa.form);
if I understand your problem, you need to check if xfa.resolveNode returns something and handle it from there.
var node;
if ( (node=xfa.resolveNode("MY_ADOBE_FORM.." + myArrayYellow[i]) )!==null){
node.ui.oneOfChild.border.fill.color.value = "255,255,254"
}
If I understand correctly, you are trying to check if all of your values in the array are valid before preforming operations on them. Just check and make sure they are not null.
EDIT: You should probably check for empty string as well.
for (var i = 0; i < myArrayYellow.length; i++) {
if (!(myArrayYellow[i] == null || myArrayYellow[i] == "")){
//Do Stuff
}
}

How do I change the name of multiple selected html values?

I have about 20 check boxes. When the user selects these and then uses an alternate submit button, I need to change the name of the name/value pair, for the selected inputs.
Why does this function only change the name of every other selected input?
function sub_d()
{
for (i = 0; i < document.checks.OGname.length; i++) //for all check boxes
{
if (document.checks.OGname[i].checked == true)
{
document.checks.OGname[i].name="newname"; //change name of input
}
}
document.checks.submit();
}
The output:
newname
'105'
OGname
'106'
newname
'107'
OGname
'108'
newname
'109'
OGname
'110'
By renaming the first element of the list you have reduced the length of the list by one and deleted the first element. Next time through the loop the previous second element is now the first, and the second is the old third.
I'm no javascript expert, but something along the lines of this might work.
function sub_d()
{
i=0;
while (document.checks.OGname.length > i)
{
if (document.checks.OGname[i].checked="true")
{
document.checks.OGname[i].name="newname";
}else{
i++;
}
}
document.checks.submit();
}
As I said, no warranty or guarantee.
Would be great if you provide a more detailed description of your scenario, but I wish that my answer be useful.
function sub_d()
{
for (i = 0; i < document.checks.OGname.length; i++) //for all check boxes
{
if (document.checks.OGname[i].type == 'CHECKBOX')
if (document.checks.OGname[i].checked)
{
document.checks.OGname[i].name="newname"; //change name of input
}
}
document.checks.submit();
}
I usually manage dom collections in this way: (I don't know if is the best way)
function sub_d()
{
var theInputs = document.checks.getElementsByTagName('input');
for (var i = 0; i < theInputs.length; i++)
{
if (theInputs[i].type == 'CHECKBOX')
if (theInputs[i].checked)
{
theInputs[i].name="newname";
}
}
document.checks.submit();
}
With your guys help I came up with this, seems to work well. Let me know if it can be improved for others to use...
function sub_d()
{
for (i = 0; i < document.checks.OGname.length; i++) //for all check boxes
{
if (document.checks.OGname[i].checked == true)
{
document.checks.OGname[i].name="newname"; //change name of input data so we know it is for other function
//By renaming the first element of the list, we have reduced the length of the list by one
//and deleted the first element. This is why we need to keep i at it's current position after a name change.
i=i-1;
}
}
//When there is only one check box left it's propert length becomes undefined.
//We will need this statement for the last undefined check box not covered in the for loop
//We can no longer index user[0]
document.checks.OGname.name="newname";
document.checks.submit();//submit these checked values to the .exe
}

Categories