Robert Hanson Robert Hanson - 7 months ago 6
Javascript Question

jQuery Change Null Into Zero With IF Failed

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
?

Answer

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);
});