Reputation: 5525
I have this jquery loop :
var total_value = 0;
$("select.dropdown").each(function() {
if (($(this).val()) = null) {
$(this).val() = 0;
}
alert ($(this).val());
total_value = parseInt(total_value) + parseInt($(this).val());
});
some of $(this).val()
still have null
value because user haven't select yet. but I need to sum all value. so, I need to convert null
into 0
in order to be calculated.
but I can't alert it because there's conditional IF
there. what's wrong with that IF
?
Upvotes: 0
Views: 3696
Reputation: 82231
If this is just for sake of calculating the sum, then you need to change the total_value
calculation to:
total_value += $(this).val() == null ? 0: parseInt($(this).val(),10);
Full Snippet:
var total_value = 0;
$("select.dropdown").each(function() {
total_value += $(this).val() == null ? 0: parseInt($(this).val(),10);
});
Upvotes: 2
Reputation: 76547
You are currently using the assignment operator =
for equality instead of one of the the equality operators ==
or ===
in your if-statement.
Additionally, the val()
function actually expects a parameter for the value you wish to set as seen below :
// This will compare your value to null
if ($(this).val() == null) {
// If it is null, it will set it to 0
$(this).val(0);
}
Upvotes: 1