suo suo - 1 month ago 12
Ajax Question

Javascript - replace elements with same class with different values

Quick one: Is it possible to replace the values of elements with the SAME class with different values?

Here's what I mean: I have this array returned by an AJAX response:

[
"$63.00 / Night",
"$68.00 / Night",
"$58.00 / Night",
"$50.00 / Night"
]


The above array is generated from a html response that looks like this:



var result = [
"$63.00 / Night",
"$68.00 / Night",
"$58.00 / Night",
"$50.00 / Night"
];

console.log(result[0]);

result.forEach(function(item)
{
var num_price = parseFloat(item.replace( /[^\d\.]*/g, ''));
num_price = num_price * 2;
console.log(num_price);

$('.gdlr-tail').html(num_price);
});

<span class="gdlr-tail">$63.00 / Night</span>
<span class="gdlr-tail">$65.00 / Night</span>
<span class="gdlr-tail">$67.00 / Night</span>
<span class="gdlr-tail">$72.00 / Night</span>





From the above, trouble kicks in on the last line of the code:
$('.gdlr-tail').html(num_price);
where it renders all the values in my
.gdlr-tail
class to be the value of the first span i.e all the values in the class are set to
126(63*2)
. This happens though my array is inside a loop. Only the first element is calculated with all the other elements being set to the value of this calculation.

Where could i be going wrong?

Answer

Iterate the .gdlr-tail elements, and not the prices. Then assign to each element the corresponding value from the array:

var result = [
  "$63.00 / Night",
  "$68.00 / Night",
  "$58.00 / Night",
  "$50.00 / Night"
];

$('.gdlr-tail').each(function(index, el)
{
    var num_price = parseFloat(result[index].replace( /[^\d\.]*/g, ''));
    num_price = num_price * 2;

    $(el).html(num_price);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="gdlr-tail">$63.00 / Night</span>
<span class="gdlr-tail">$65.00 / Night</span>
<span class="gdlr-tail">$67.00 / Night</span>
<span class="gdlr-tail">$72.00 / Night</span>

Comments