I have a small app that should get two price values from elements on a website.
This is achieved by iterating over the .textContent of the two querySelectors (cardStartBidValueString and cardCurrentBidValuesString).
Then I also get all elements with a specific CSS selector (cardBg).
What I want to do is to check if the start price and the current bid price are both < userInputBidPrice (which is the cap of what a user wants to bid) and if this is true, then change the background color of that item so the user can directly see a potential deal. In sum there are 20 elemenets that include those two prices. So basically I want to change the background of all elements for which above condition is true.
Unfortunately its nor working. if I say cardBg[i].style['background-color'] = '#0311c3'then it only changes the color when the CurrentBidPrice is < userInputBidPrice and if I change it to cardBg[x].style['background-color'] = '#0311c3' then it colors all item if the startBidPrice is < userInputBidPrice
For some reason it is not checking if both conditions are true.
This is my code:
function deals() {
let userInputBidPrice = prompt('Set max Bid Price:');
let cardCurrentBidValuesString = document.querySelectorAll('.auction > .auctionValue:nth-child(2) > .currency-coins.value');
let cardStartBidValueString = document.querySelectorAll('.auction > .auctionStartPrice.auctionValue > .currency-coins.value');
let cardBg = document.querySelectorAll('.rowContent.has-tap-callback');
for (let i = 0; i < cardCurrentBidValuesString.length; i++) {
cardsCurrentBidPrice = cardCurrentBidValuesString[i].textContent.toString().split(',').join('');
if (cardsCurrentBidPrice === '---') {
cardsCurrentBidPrice = 0;
}
parsedCardsCurrentBidPrice = parseInt(cardsCurrentBidPrice);
for (let x = 0; x < cardStartBidValueString.length; x++) {
cardsStartBidPrice = cardStartBidValueString[x].textContent.toString().split(',').join('');
if (cardsStartBidPrice === '---') {
cardsStartBidPrice = 0;
}
parsedCardsStartBidPrice = parseInt(cardsStartBidPrice);
}
if (parsedCardsCurrentBidPrice < parseInt(userInputBidPrice) && parsedCardsStartBidPrice < parseInt(userInputBidPrice)) {
cardBg[i].style['background-color'] = '#0311c3';
}
}
}
deals();
Related
I have an ecommerce product that I sell a box of assorted flavor bagels. The max amount of flavors per box is 12. I have a number input field for each of the 12 flavors as shown in the screenshot below.
I was able to use JavaScript to limit each individual number field from exceeding 12 but I am trying to make it where the other input fields disable once the total of all fields reaches the max of 12.
The code below is what I am using to get the total of all the fields.
but at the moment It only prevents the increase of number on an individual field once it reaches 12.
I want to prevent from adding more than 12 in total from all fields combined which will complete the box of 12 bagels
const totalMaxQty = 12;
getAllInputs.forEach(allInputs);
function allInputs(value) {
value.addEventListener("input", function(e) {
e.preventDefault();
sumTotal();
});
}
function sumTotal() {
let sumValue = document.querySelectorAll('.wapf-field-input input[type=number]');
let currentTotal = 0;
for (let i = 0; i < sumValue.length; i++) {
if (parseInt(sumValue[i].value)) {
currentTotal += parseInt(sumValue[i].value);
};
}
}
for (let i = 0; i < getAllInputs.length; i++) {
getAllInputs[i].max = totalMaxQty;
}
Vanilla JavaScript only, please.
I see that you are actually returning nothing in the sumTotal(), so simply calling it inside allInputs doesn't have any effect.
function sumTotal() {
let sumValue = document.querySelectorAll('.wapf-field-input input[type=number]');
let currentTotal = 0;
for (let i = 0; i < sumValue.length; i++) {
if (parseInt(sumValue[i].value)) {
currentTotal += parseInt(sumValue[i].value);
};
}
return currentTotal
}
About disabling the input fields, I suggest you use event delegation.
Put all the input fields and their labels in a container and set the event listener on it. So you don't need to set an event listener on each of the input fields in a for loop.
const container = document.getElementById("container")
container.addEventListener("input", handleInputs )
function handleInputs() {
let currentTotal=sumTotal()
if (currentTotal===12) {
for (let i = 0; i < getAllInputs.length; i++) {
getAllInputs[i].disabled = true;
}
}
}
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.
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
Imagine you have a product page. On this page there are two select inputs with options in them.
There is one for Size and Colour. This can change depending on the product, e.g. a curtain might have a size, length and colour (three select menus).
The array is created dynamically (based on each select menu and its options):
var dynamicArr = [],
i,
j,
opt,
$('.select');
for (i = 0; i < select.length; i += 1) {
opt = select.eq(i).find('option');
if (dynamicArr[i] === undefined) {
dynamicArr[i] = [];
}
for (j = 0; j < opt.length; j += 1) {
dynamicArr[i].push(opt.eq(j));
}
}
Imagine the page had a size and colour drop-down. The above would create an array like this:
dynamicArr = [['size'], ['color']]
I want to loop through each of these separately (in order to get individual values and compare them).
My problem starts here. A dynamic array might have a length of 1, 2, 3, 4, 5, 6 (depending on the select options on the page). I therefore can't do this as there won't always be two selects
for (i = 0; i < dynamicArr[0].length; i += 1) {
}
for (i = 0; i < dynamicArr[1].length; i += 1) {
}
How would I go about finding out the length and looping individually like the above e.g. if there are three selects, it will automatically know there are this many and loop through them like above.
If you are still confused, let me know.
Thanks.
You can always use Array.forEach
dynamicArr.forEach(function(el){
console.log(el);
});
I hope I didn't get you wrong, but here's a solution:
for(i = 0; i < dynamicArr.length; i++) {
for(j = 0; j < dynamicArr[i].length; j++) {
// do something here..
}
}
you should try something like this:
dyn.forEach(function(el){//dyn is the dynamic array
console.log(el); //logs to console
});
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;