Reputation: 628
The data is obtained in the template in this way (python / jango), as a result the number of tags p with the class, the data from which are extracted, changes dynamically
My html:
{% for product in items %}
<li>
<p>{{ product.item_title }}</p>
<p class="product-quantity">{{ product.quantity }}</p>
<p>{{ product.price }}</p>
</li>
{% endfor %}
My js:
var quantity_block = $('.product-quantity'),
quantity_number = parseInt(quantity_block.text());
console.log(quantity_number);
if (quantity_number < 10) {
quantity_block.css(
{'background-color': 'red'}
)
}
but this condition will never be fulfilled, since I have this selector the same for 6 p tags, and the values come from the database (2, 4, 15, 3 ....) and they are concatenated - 24153, I get such a number on the output .
Upvotes: 0
Views: 44
Reputation: 21881
Either use .each()
$('.product-quantity').each(function () {
var quantity_block = $(this),
quantity_number = parseInt(quantity_block.text());
if (quantity_number < 10) {
quantity_block.css('background-color', 'red');
}
});
Or .css( propertyName, function )
$('.product-quantity').css('background-color', function (index, oldValue) {
var quantity_number = parseInt($(this).text());
return quantity_number < 10 ? 'red' : oldValue;
})
Upvotes: 2
Reputation: 4527
The quantity_block
contains collection of elements. Thus, you need to iterate the elements of this collection using each method. Try to use following
$('.product-quantity').each(function() {
var quantity_number = parseInt($(this).text());
console.log(quantity_number);
if (quantity_number < 10) {
$(this).css('background-color', 'red');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="product-quantity">7</p>
<p class="product-quantity">15</p>
<p class="product-quantity">8</p>
Upvotes: 0