JavaScript undefined variable getting value from page class - javascript

I have a bookmarklet which takes some information from the page the user current is on which they an then save to there account.
One such peace of information is a price of an item they might be looking at. To grab the price from the page I have the below javascript:
input = this.createInput("price", "hidden");
var prices=new Array("price","kfs-price","pricesize","salesprice","money","ourPrice","product-price","memo_fp_prix_final"
,"atrPrice","product_price");
var price = 0;
for (var i = 0; i < prices.length; i++){
var priceEls = document.getElementsByClassName(prices[i]);
for (var a = 0; a < priceEls.length; a++) {
price = priceEls[a].innerText;
i = 1000;
}
}
input.setAttribute("value", price);
this.form.appendChild(input);
The prices array is based on looking at some common well known sites and what class name they give for the area the price is put into.
How even on pages that for example have a price class name the variable 'price' when added to the form still comes back 'undefined'.
I cant see anything wrong with the code so was hoping someone can see the issue or knows of a better method?

try with innerHTML : http://jsfiddle.net/vDFpR/
for (var a = 0; a < priceEls.length; a++) {
price = priceEls[a].innerHTML;
i = 1000;
}
it's may be related to this : 'innerText' works in IE, but not in Firefox

i think this line
var priceEls = document.getElementsByClassName(prices[i]);
// taking an instance of this inside the loop
var priceEls = document.getElementsByClassName('price');
Now i don't understand your innerloop
for (var a = 0; a < priceEls.length; a++) {
price = priceEls[a].innerText;
i = 1000;
}
priceEls is giving you an element only
what is this line doing
//price = priceEls[a].innerText;

Related

Validation of 2 or more groups of radio buttons each containing 4 radios

So I had to include this part in one of our class projects. We were asked to create a quiz webpage with radios and checkboxes, and then to write a JavaScript function to validate the radios. Now, I know that these radios can be verified easily by individuals for loops for each group, but that doesn't sound practical when I have a large number of these groups in my code. So I tried the following code:-
function quizRadioFilled()
{
var check = false;
var c = 0;
var x = 0;
var radiob = [];
radiob[0] = document.getElementsByName('q1');
radiob[1] = document.getElementsByName('q2');
radiob[2] = document.getElementsByName('q3');
radiob[3] = document.getElementsByName('q4');
radiob[4] = document.getElementsByName('q5');
radiob[5] = document.getElementsByName('q9');
radiob[6] = document.getElementsByName('q10');
for(var i = 0; i <= 6; i++)
{
for(var j = 1; j <= radiob[i].length; j++)
{
if(radiob[i].checked)
{
c = 1;
break;
}
}
if(c == 0)
{
check = false;
}
}
if(!check)
{
alert('Please attempt all the questions....');
}
}
I first stored the names of each group in an array. Then looped through this to validate each of these groups. I want to display the alert if a group has no radio button selected. But I am not getting the required result. Though I have completed this project now, I would still like to get this function to work. Kindly provide some suggestions.
You never set check to true anywhere, so it is always false.
radiob[i] is an array (or, more precisely, a NodeList), so radiob[i].checked is always undefined.
Arrays in JavaScript start indexing at 0, and this applies to NodeList as well. So your for (var j = 1; j <= radiob[i].length; j++) loop is not correct.
If you fix these problems then your function should work correctly.

Getting through all entries in JS by queryselector

I'm trying to get some informations from the page.
If there is one entry I can do that by
var z = document.querySelector('div.class').innerText;
and then get it by +z somewhere where I need the value.
But if there are more entries it will get only first.
I'm trying to do sth like that to get them all:
var x = document.querySelectorAll('div.class');
var i;
for (i = 0; i < x.length; i++) {
x[i].innerText;
}
But definitely something's wrong with this code. I'm not really familiar with JS, could you help me how to get all entries?
You can achieve that by using getElementsByClassName('class').
The script would be sort of:
let list = document.getElementsByClassName('class');
for (let i = 0; i < list.length; i++) {
console.log(list[i].innerText);
}
https://jsfiddle.net/esjcaqwb/
Your code looks ok, heres a working example that might be useful.
var x = document.querySelectorAll('.example');
var r = document.querySelectorAll('.result')
var i;
for (i = 0; i < x.length; i++) {
r.innerText += x[i].innerText;
}
What was going wrong with your code? In the example you provided, you're getting the value but not doing anything with it.
With your actual code you are not doing anything in the loop, the statement x[i].innerText; does nothing.
If you want to get these elements contents in an array you can use:
var results = Array.from(x).forEach(function(el){
return el.innerText;
});

Why is my JavaScript array showing a two element count when there is supposed to be only one?

I have an JS Array that is supposed to show only one element. It does, however its index is 1 rather than 0 and the count is 2. Also the array does not show a 0 index.
My code:
var _UnitOfMeasureRelatedUnitData = [];
var rows = $('#jqxUOMRelatedUnitsDropdownGrid').jqxGrid('getrows');
var RecordCount = 0;
if (rows.length !== 1 && rows[0]["UOMRelatedUnit_Name"] !== ""){
for(var i = 0; i < rows.length; i++){
var row = rows[i];
var _row = {};
if(row.UOMRelatedUnit_AddItem !== F) {
RecordCount += 1;
_row["Name"] = $("#txtUnitOfMeasureSetName").val();
_row["Active"] = T;
_row["UnitOfMeasureTypeID"] = $("input[type='radio'][id='rblUnitOfMeasureType']:checked").val();
_row["BaseUnitID"] = $("input[type='radio'][id='rblUnitOfMeasureBaseUnit']:checked").val();
_row["RelatedUnitDisplayOrder"] = RecordCount;
_row["RelatedUnitName"] = row.UOMRelatedUnit_Name;
_row["RelatedUnitAbbreviation"] = row.UOMRelatedUnit_Abbreviation;
_row["RelatedUnitConversionRatio"] = row.UOMRelatedUnit_ConversionOfBaseUnits;
_row["UnitOfMeasureSetID"] = UnitOfMeasureSetID;
_UnitOfMeasureRelatedUnitData[i] = _row;
}
}
....
}
In my JQx Grid, I have at least four choices. For this issue, Ive only selected the 2 choice in the Grid and its AddItem value is True, everything else is False.
What do I need to change in my logic as I can not see it at this point?
EDIT 1
I overlooked the placement of RecordCount += 1;, I will try moving it to the end of the assignments and see what happens.
EDIT 2
The placement made no difference.
Maintain another variable for indexing your data like this
var index=0; // place this outside of for loop
_UnitOfMeasureRelatedUnitData[index++] = _row;
you don't need RecordCount += 1; .
you can get the rowscount by using _UnitOfMeasureRelatedUnitData.length

Add two parameters in function into "then" protractor

It is quite clear. I have an array with some links and I want to build a loopto try all of them, but the problem is that link is always 3. It means that it read the last number in my array. Why? How can I fix it?
var categories = ['1','2','3'];
for( var i = 0; i < categories.length; i++ ) {
var link = '/'+categories[i];
browser.get(link);
browser.sleep(2000);
browser.driver.getCurrentUrl().then( function(url) {
expect(url).toMatch(link);
});
}
and I have list of divs and I want to read randomly infos from them. So I made the following
chosenOffer = Math.floor( (Math.random() * count ) + 1);
offer = element.all( by.className('offer')).get( chosenOffer );
But it shows always error message chosenOffer object...
This is a classic closure problem that is described in detail in:
Using protractor with loops
In your case, just let expect() resolve the promise:
var categories = ['1','2','3'];
for (var i = 0; i < categories.length; i++) {
var link = '/' + categories[i];
browser.get(link);
browser.sleep(2000);
expect(browser.driver.getCurrentUrl()).toMatch(link);
}

How to find the count of images that have same file name?

Can you please help me how to find the no.of images for same file name,
var images =["Cat.png", "Cock.png","Dog.png","Parrot.png","Penguin.png",
"Rabbit.png","Parrot.png"];
here I have 7 images in the array...
I need count like..
Cat:1
Parrot :2
Penguin:1
Please give me the suggestion
Thanks,
Rajasekhar
The usual solution is to use an object as a map to make the link between the keys (name of the files) and the count :
var count = {};
for (var i=images.length; i-->0;) {
var key = images[i].split(".")[0]; // this makes 'Parrot' from 'Parrot.png'
if (count[key]) count[key]++;
else count[key] = 1;
}
Then you have, for example count['Parrot'] == 2
Demonstration : http://jsfiddle.net/tS6gY/
If you do console.log(count), you'll see this on the console (Ctrl+Uppercase+i on most browsers) :
EDIT about the i--> as requested in comment :
for (var i=images.length; i-->0;) {
does about the same thing than
for (var i=0; i<images.length; i++) {
but in the other directions and calling only one time the length of the array (thus being very slightly faster, not in a noticeable way in this case).
This constructs is often used when you have a length of iteration that is long to compute and you want to do it only once.
About the meaning of i--, read this.
i-->0 can be read as :
decrements i
checks that the value of i before decrement is strictly positive (so i used in the loop is positive or zero)
Not sure about efficiency, but this should do:
var images =["Cat.png", "Cock.png","Dog.png","Parrot.png","Penguin.png","Rabbit.png","Parrot.png"];
images.forEach(function(img){
var count = 0;
images.forEach(function(image, i){
if(img === image){
delete images[i];
count++;
}
});
console.log(img, count);
});
DEMO
You can keep unique keys in an array and use another array for counting the frequency:
var images =["Cat.png", "Cock.png","Dog.png","Parrot.png","Penguin.png","Rabbit.png","Parrot.png"];
var counts = [];
var keys = [];
for (i = 0; i < images.length; i++){
if (!counts[images[i]]) {
counts[images[i]] = 0;
keys.push(images[i]);
}
counts[images[i]]++;
}
for (i = 0; i < keys.length; i++) alert(keys[i] + " : " + counts[keys[i]]);
​
Here is a demo : http://jsfiddle.net/e5zFC/1/

Categories