Retrieve all DOM elements in javascript - javascript

My application needs to retrieve all DOM elements in javascript and
and put there values into one variable
i.e
if my application is having three text boxes then i want there values in comma separated form in javascript variable

If you want all DOM elements, which you probably don't, but if you do...
document.getElementsByTagName('*');
What I think you want is something like this
var form = document.getElementById('my-form').
var inputs = form.getElementsByTagName('input');
var inputsCsv = [];
for (var i = 0, length = inputs.length; i < length; i++) {
if (inputs[i].type === 'text') {
inputsCsv.push(inputs[i].value);
}
}
inputsCsv = inputsCsv.join(',');

in below example i am taking values of all textboxes of a table. you can pass form name there.
var frm = document.getElementById('tblemail').getElementsByTagName("input");
var len = frm.length;
var myval='';
for (i=0;i< len;i++)
{
if (frm[i].type == "text")
{
if(myval =='')
{
myval = frm[i].value;
}else{
myval += ',' + frm[i].value;
}
}
}

Related

Looping through a table rows with comparisons using VUgen

I have a table I need to compare each of the values within to an existing parameter.
I have this Xpath here: //*[#id="maincontent"]/messages/div/div[1]/div[1]/table/tbody/tr[1]/td[4]/div/span
and would like to insert an increment variable from the loop to go through the /tr/ in the table only.
Here is what i have so far:
var i;
var max = 10;
var xpathleft = `*[#id="maincontent"]/messages/div/div[1]/div[1]/table/tbody/tr[`;
var xpathright = `]/td[4]/div/span`;
for (i = 1; i < max, i++)
{
var currentXpath = string.concat(xpathleft, i, xpathright);
}
if (currentXpath.innerHTML == PartnerIDs)
{
lr_log_message("Match Found!");
}
This is currently sitting in an Evaluate Javascript step in TruClient/VUgen and is giving me Syntax Error: Unexpected Token )
The element here doesn't have any ID I can reference and looks like this: Partner ID
and has been difficult to pull the needed Partner ID text within code.
Some of your JavaScript syntax is incorrect.
Try this:
var i;
var max = 10;
var xpathleft = `*[#id="maincontent"]/messages/div/div[1]/div[1]/table/tbody/tr[`;
var xpathright = `]/td[4]/div/span`;
for (i = 1; i < max; i++){
var currentXpath = `${xpathleft}${i}${xpathright}`;
if (currentXpath.innerHTML == PartnerIDs) {
lr_log_message("Match Found!");
}
}

Javascript - Seperate all IPs on page and use them as strings

I'm trying to grab all IPs on a specific page and run a function on each of them; however I can only find (through research) how to grab all IP's on the page as a single string. Not very proficient in JS, as you may be able to tell.
Grab as single string:
var markup = document.getElementsByClassName('border_wrapper')[0].innerHTML;
alert(markup.match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g).join("\n"))
I'm assuming I'll need a for loop to run them in a function. resolve(newstring);
The .join makes a string, remove it;
var markup = document.getElementsByClassName('border_wrapper')[0].innerHTML;
var list = markup.match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g);
if (list != null) {
for (var i = 0; i < list.length; i++)
alert(list[i]);
}
Using a cache to prevent repeats;
var markup = document.getElementsByClassName('border_wrapper')[0].innerHTML;
var list = markup.match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g);
if (list != null) {
var processed = {};
for (var i = 0; i < list.length; i++) {
if (!processed[list[i]])
{
processed[list[i]] = true;
alert(list[i]);
}
}
}

Get the value for each control from a list of elements?

I'm struggling to get the input value from a control in JavaScript, and I think it may have something to do with the collection of controls I'm looping through.
My page consists of many input controls with decimals in them. I'm only interested in controls starting with the name 'txtinput', and I need to tally up the values in each one. However, when I do this with the code below, all I seem to be getting out is a JSON looking string for each element.
function TallyPoints() {
var eles = [];
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.indexOf('txtpoints') == 0) {
total += document.getElementsByName(inputs[i].name)[0].value;
}
}
alert('Total: ' + total.toString());
};
What I end up with is a value that looks like this:
Total: 0{"enabled":false,"emptyMessage":"","validationText":"333.33","valueAsString":"333.33","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"333.33"}{"enabled":false,"emptyMessage":"","validationText":"5.66","valueAsString":"5.66","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"5.66"}
Any ideas?
You probably want parseFloat() so your addition works properly (fiddle):
var inputs = document.querySelectorAll("input[name^=txtpoints]");
var total = [].reduce.call(inputs, function (p, c) {
return p + (parseFloat(c.value) || 0);
}, 0);
See also parseInt(), isNaN(), and Array.prototype.reduce()
Try this:
function TallyPoints() {
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.indexOf('txtpoints') == 0) {
var val = parseFloat(inputs[i].value);
if (!isNaN(val)) {
total += val;
}
}
}
alert('Total: ' + total);
};
parseFloat is needed to convert the input from a string to a number, so that + will do addition rather than concatenation. There's no need to use getElementsByName, since you already have the element in inputs[i]. There's no need to use total.toString(); concatenating a number to a string converts it automatically.
The if (!isNan(val)) test skips over the inputs that don't contain numbers.
You could also use document.querySelectorAll('input[name^=txtpoints]') to find the relevant input elements in one step.

Search Box Function Not Eliminating Correct Value

I am trying to make a simple website where the user types input into a search box, and every time a key is press, their input is compared against the first row of a 2 dimensional array which checks for character matches. If the character they input doesn't match anything, I want it to remove that specific bucket of the array. I have attempted to write basic code for this I thought would work, and have it up at the demo site linked. (Sorry I am just using a free host and havn't optimized the equation table at all so bear with it)
http://fakefakebuzz.0fees.net/
As you can see, the function is not eliminating the appropriate table rows. For example, typing "A" should not eliminate the "Average Current Equation" row because the first letter of that is A, which means matches should not = 0.
I have been looking through this code all morning, and cannot find where I went wrong. I also want to stick to vanilla js.
Any help?
Thanks so much.
I just debugged your code, and the function you use is narrowTable. first remove onkeypress from body node
<body onload="printTable()" onkeypress="narrowTable()">
and add onkeyup instead to you input, like this:
<input type="search" name="equationSearch" id="equationSearch"
placeholder="Equation Search" autofocus="" onkeyup="narrowTable()">
because when you use onkeypress the key value hasn't been added to the input box and your input value has no value in your function, which is:
function narrowTable() {
var newTableContent = "";
var matches = 0;
var input = document.getElementById("equationSearch").value;
//input has no value
for (var i = 0; i < tableData.length; i++) {
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
matches = 0;
}
for (var i = 0; i < tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
document.getElementById("table").innerHTML = newTableContent;
}
the other problem your code has is after printing your table, your tableData variable has changed because you have removed some of indexes. you should reset the tableData to its original value or you can do:
function narrowTable() {
//create a copy of your original array and use currenttableData instead
var currenttableData = tableData.slice();
var newTableContent = "";
var matches = 0;
//your code
}
the other problem here is the way you search for your input value:
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
you can easily do this, instead:
if(tableData[i][0].search("input") == -1){
tableData.splice(i, 1);
}
First, to check if a string is a substring of another string, you can use indexOf. It will return -1 if the string is not found in the other string.
Second, you shouldn't alter the array while you are still looping through it, unless you make sure to alter the counter variable (i in this case) appropriately.
var dataToRemove = [],
i;
for (i=0; i<tableData.length; i++) {
if(tableData[i][0].indexOf(input) == -1) {
// add the index to the to-be-removed array
dataToRemove.push(i);
}
// remove them in reverse order, so the indices don't get shifted as the array gets smaller
for(i = dataToRemove.length - 1; i >= 0; i--) {
tableData.splice(i, 1);
}
dataToRemove = [];
for (i=0; i<tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
I haven't tested this code, but it should at least give you a better idea of how to make this work.

Check series of checkboxes according to string

I have group of checkboxes nearly equals to 100 all are with name checkbox1...checkbox1oo. I am getting a string from database in the bit format. Now I need to check checkboxes using for loop according to everyposition for string..
just taking example. String is 10010. that means I have to select checkbox 1st AND 4th. Hows it will be possible.
for (i=1;i<=5;i++)
{
check every position of sting==1
than document.formname.checkbox[i]==checked.
}
I wish to do something like that.
for( var i = 0, l = string.length ; i < l ; i++ ) {
if( string.charAt(i) === "1" ) {
document.forms[formname]['checkbox' + i].checked = true;
}
}
where string is the string from your database, and formname is the id of the form you're manipulating
Get all the tags, loop through, get check boxes, build the string.
var elements = document.getElementsByTagName('input');
var str = "010101";
for(var i = 0; i< elements.length; i++) {
if (elements[i].type == "checkbox") {
var index = +(elements[i].name.match(/\d+/g)[0]); // get index
elements[i].checked = !!(+str.charAt(index -1));
}
}
http://jsfiddle.net/UMuxP/
!!(+str.charAt(index -1))
could easily be:
str.charAt(index -1) === "1"

Categories

Resources