Javascript - check Checkboxes does not work - javascript

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).

Related

.hide() is not a function error when executing from a loop

I want to be able to loop over a few different labels and hide their content based on if a radio button is check or not. This is the solution I came up with, but I keep getting an error in the console.
var hazardOptions = $(".js-hazardous-option");
var hazard = $("input[name=Hazardous]");
for (var i = 0, len = hazard.length; i < len; i++) {
if (hazard[i].id === "HazardousYes" && hazard[i].checked) {
for (var ii = 0, length = hazardOptions.length; ii < length; ii++) {
hazardOptions[ii].show();
}
} else if (hazard[i].id === "HazardousNo" && hazard[i].checked) {
for (var iii = 0, leng = hazardOptions.length; iii < leng; iii++) {
hazardOptions[iii].hide();
}
}
}
The error I get is:
hide() is not a function
Not sure what I'm missing, I've tried having a look online for a similar issue, but with no luck. I'm pretty sure that the problem is here: hazardOptions[iii].hide(); but not really sure why and/or how to fix it.
When you have a list of objects from a JQuery selector, if you try to access them via index you actually get the DOM element back and not the JQuery object. It's confusing for sure but it is in the documentation.
What you effectively need to do is turn it back into a JQuery object:
$(hazardOptions[iii]).hide();
Or you can use the eq() function with does provide the JQuery object ad thus still has the hide() function:
hazardOptions.eq(iii).hide();
Most probably you need to wrap it with $
$(hazardOptions[ii]).hide()
As you currently have it, if hazard.id === "HazardousYes", you are showing all hazardOptions, and if it is "HazardousNo"you are hiding all of them.
You can call .show() and .hide() on a jQuery collection and it will apply that to all elements in the collection. The below code will replicate the logic of your original code, however, the hazardOptions final show/hide state will be solely determined by the last hazard that is checked and has an id equal to "HazardousYes" and "HazardousNo". This may be what you want, but I would imagine it's not.
var hazardOptions = $(".js-hazardous-option");
var hazards = $("input[name=Hazardous]");
hazards.each(function (index, hazard) {
if (hazard.checked) {
if (hazard.id === "HazardousYes") {
hazardOptions.show();
} else if (hazard.id === "HazardousNo") {
hazardOptions.hide();
}
}
}
Edit - Come to think of it, if you don't have elements with duplicate IDs, You can make this really simple:
hazardOptions.show($("#HazardousYes").is(":checked"));
hazardOptions.hide($("#HazardousNo").is(":checked"));

Select at least one option in HTML

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;

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

Javascript Disable form field element by id (id is an array)

I am building a recurring events module to drop into a form, this module has several fields.
I have named and ID'd each of this module using array notation. EG:
id='recurring_event_options[yearly][by_date_day_number]'
In my JS I need to target all fields with the matching id recurring_event_options
I have some JS working nicely that enables (non disabled) fields as needed, but before i run this i need to disable all the fields in this module.
I have been using somthing similar to this to disable the fields:
function disableForm(theform) {
if (document.all || document.getElementById) {
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (true) {
formElement.disabled = true;
}
}
}
}
As you can see, that going to hit every field in the form - thats not what i want - only to disable the fields that belong to the recurring_event_options parent ID.
I have a feeling I probably cant use [] notation in IDs, so suggestions welcome!
First of all i think it is not a good idea to use [].
You can use a hyphen - or underscore _ to separate the values:
id='recurring_event_options-yearly-by_date_day_number'
Now you can disable:
function disableForm(theform) {
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (formElement.id.indexOf("recurring_event_options") !== -1) {
formElement.disabled = true;
}
}
}
This should work. but in my opinion it will be much better if you use a class instead:
<input type="text" class="recurring_event_options prop2 prop3" />
because the class attribute is designed to support multiple values, separated by a space

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