count number of inputs which have value - javascript

js noob here - I'm trying to count the number of inputs that have a value out of a calculated number of them. The code I came up with trying to achieve that is the following:
var fields = document.querySelectorAll('[id^=example-]'), count = 0;
for (var z = 0; z <= fields.length; z++) {
if (fields[z].value != "") {
count = count + 1;
}
console.log('count is: ' + count);
}
Context: there are 3 inputs total and the above code executes on a click event.
Now the first time, this obviously runs fine if for example I set the value of the first input out of the three and returns [1]. The second time I update the same field's value, the counter increases again (logically).
Now, what I would like to achieve is to check all three inputs at the time the event fires & count how many of them have a value (and not increase the counter furthermore if they are already counted as having a value in the previous fire event).
Any help would be greatly appreciated. Thanks!

Shorter
const count = [...document.querySelectorAll('[id^=example-]')]
.filter(fld => fld.value.trim() !== "")
.length

Related

For loop homework

I have homework and these are my instructions:
create javascript 06.js with a general function: addThemUp()
There is NO HTML page. There is NO EVENT HANDLER.
The function receives two parameters. They go between (..).
Use any names you want for the parameters but you could use descriptive names
Add all integers from the first parameter to the second.
All you need to do is use a for() loop and return the total.
Return the total of the integers. Use return because this is a general function.
Here is my code
function addThemUp(earlier,later) {
var total = 0;
for (i = 0; i <= earlier; i ++) {
total = total + 0;
};
return total;
};
For some reason this one is messing up bad. We were able to do this exact same thing with Count but adding up and array seems to be different. When I run it through the grader I'm only receiving 25% grade.
You need to make use of both earlier and later in your loop:
function addThemUp(earlier,later) {
var total = 0;
for (i = earlier; i <= later; i ++) {
total = total + i;
};
return total;
};
Shouldn't it be using
i <= later
As it would stop on the first value otherwise?
I'll point out two things that could help you on your way.
First: this line
total = total + 0;
Think about what it's doing for a bit.
total (which starts as 0) is adding... 0... to itself. ;)
Next, this line:
for (i = 0; i <= earlier; i ++) {
IIRC, earlier is the first of the two numbers you're concerned about.
That part of the for loop says "stop when this condition is met." ;)

Include duplicates in for and if loop of array as count number is too small

I'm new to javascript so any help would be greatly appreciated.
What I'm trying to do is cycle through every element in the array and count the number of times the value of an element matches a given condition (even if the value is duplicated).
function loaddata(xml) {
var count = 0;
var i;
var xmlDoc = xml.responseXML;
var z = xmlDoc.getElementsByTagName("group");
if (value1 <= value2) {
for (i = 0; i < (0 + z.length); i++) {
if (z[i].getElementsByTagName("name")[0].childNodes[0].nodeValue == "John") {
count++;
}
}
}
$('#count1').html(count);
};
The count value outputted is too small. I believe the reason for this that the for loop isn't iterating through all elements in the array. When I remove the second if loop and output the count for just the for loop this value is also too small. I believe that the for loop isn't searching through the duplicate elements of the array (i.e. it is ignoring them so that they aren't then fed into the second if loop). Is it possible to specify that the for loop include duplicates?
Do a console.log(z[i].getElementsByTagName("name")) and open your browser's console, and see if that array has data in it.
Then console.log(z[i].getElementsByTagName("name")[0].childNodes) and make sure you have nodes in it.
Also, do you have many <group></group> tags? Because that's what you are selecting with var z = xmlDoc.getElementsByTagName("group");
I hope that helps,

How can I add javascript to a PDF document to count the number of checked boxes and enter the value into a textbox area?

So I have a PDF doc that has 25 check boxes called "cb1" through "cb25". I would like to be able to count the number of boxes that are checked and put that count into a text box area called "Points".
I'm not very familiar with either JS or PDF form creation but from what I've been able to dig up I think I'm close to getting it to work.
I have added the following code to the document level:
function CountCheckBoxes(aFieldsNames) {
// count field names that have been selected
var count = 0;
// loop through array of field names
for (i = 0; i < aFieldNames.length; i++) {
// for field names with a value of not Off increment counter
if (this.getField(aFieldNames[i]).value != "Off") count++;
} // end loop of field names
// return count
return count;
} // end CountCheckBoxes
I've tried adding the following code text box properties to execute JS on mouse up and as a calculated value, neither of which seem to work to populate the text box with a count of checked boxes.
// var define field names to be tested
var aFields = new Array('cb1', 'cb2', 'cb3', 'cb4', 'cb5', 'cb6', 'cb7', 'cb8', 'cb9', 'cb10', 'cb11', 'cb12', 'cb13', 'cb14', 'cb14', 'cb15', 'cb16', 'cb17', 'cb18', 'cb19', 'cb20', 'cb21', 'cb22', 'cb23', 'cb24', 'cb25');
// count field names that have been selected
event.value = CountCheckBoxes(aFields);
The code below should be added to the text field that keeps count of the boxes. To do so, right click on the form field then Properties -> Calculate -> Custom Calculation Script -> "Edit...".
var sum = 0;
for ( i = 1; i < 26; i++ ) {
f = "cb" + i;
field = getField(f);
if (field.isBoxChecked(0)) {
sum = sum + 1;
}
}
event.value = sum;
This is tested and working in an actual document. Here are some details about the code:
There is a loop that goes over all 25 fields, and creates a string for each one of their names. The string values are "cb1", "cb2" etc. Then gets the field by name. The isBoxChecked(0) field method, will return true if the box is checked. If a box is checked, the code will bump up the sum of all checked fields. When it's all done, the sum is assigned to the current text field.
Here is a link to the JS for Acrobat reference. It's quite useful when putting together samples like the one above.

Result of FOR-loop if there is no related item

in a Podio calculation_field A I sum up the numbers of each related item (from another app) which contain "searchstring_1" in a text_field, in calculation_field B all related items which contain "searchstring_2"
No problem with the following code - IF there exists a related item. But if there exists no related item the "1" (= "nothing found"?) is displayed as "result". I tried several things, but can't find a solution for a calculation like: IF there is no related item then result = 0 (or "" or null), else let run the for-loop. Has anybody a tip what I can do?
Thanks,
Rainer
var str = all of text_field;
var num = all of number_fields;
var total = 0;
for(var i = 0; i < num.length ; i++) {
if (str[i].indexOf("searchstring_1") === 0) {
total += num[i];
}
}
The calculation field always returns the last used value if you don't explicitly specify the return value. Maybe in your case the last value of i, str[i].indexOf("searchstring_1") would return -1, I think...
To make sure that the value of totalis returned, simply add
total;
at the end of your calculation field value.
Enjoy,
Michael / Hamburg

JavaScript validation, prevent duplicate input fields

I have a form with 10 Select Lists all have the same items. The items are populated from a PHP/MySQL array. The user needs to select one item per select list. I need to prevent the user from selecting the same item twice before submitting the form.
function checkDropdowns(){
var iDropdowns = 10;
var sValue;
var aValues = new Array();
var iKey = 0;
for(var i = 1; i <= iDropdowns; ++i){
sValue = document.getElementById('test' + i).value;
if ( !inArray(sValue, aValues) ){
aValues[iKey++] = sValue;
}else{
alert('Duplicate!');
return false;
}
}
return true;
}
Use javascript to add an event listener on the value change of the selects. That function would then loop through the selects taking the values into memory after having compared it to the values it had already. If the loop finds that the current select has an option that is already selected, put it back to default value and display a little message...
Or, still on a change event, take the value of the just selected item and remove all the items of this value in the 10 selects. So at the end the user will only have 1 choice, since he only sees the options he can choose. But be careful, if the user changes his mind on one select, make sure you add back the option you removed in the first place.
Option 2 is to be prefered as a user point of view, you will cause less frustration.
EDIT:
The code you are providing already does quite a lot... All you need now is something to revert the change if it is invalid:
var defaultValues = [];
function onLoadSelect(){//Please execute this on document load, or any event when the select are made available.
var iDropdowns = 10;
var iKey = 0;
for(var i = 1; i <= iDropdowns; ++i){
var sValue = document.getElementById('test' + i).value;
defaultValues['test' + i] = sValue;
}
}
Then, in your function's else, reset the value according to the defaults we have gathered:
else{
alert('Duplicate!');
document.getElementById('test' + i).value = defaultValues['test' + i];
return false;
}
I have written code, i think it can be improved but it works as you asked.
Put it in inside script tag under body so it loads after document.
Put id names of select/dropdown elements in id array.
Take a look: //took me 3 hours O_O
http://jsfiddle.net/techsin/TK9aX/15/
i think i need better strategy to approach programming.

Categories

Resources