We need to let the user enter a number in an <input type='number'>
and, if it's negative, the negative
style will apply, which will make the displayed text red. However, I am having trouble getting the if
statement to work.
HTML:
<span class="input">
<input type="text" value="-">
<input type="number" class="hidden">
</span><br>
<span class="input">
<input type="text" value="-">
<input type="number" class="hidden">
</span>
$(this).prev().addClass('negative');
doesn't work in the if
statement in the following:
$(document).ready(function(){
$('.input [type="text"]').on('focus', function(){
$(this).next().removeClass().focus();
$(this).addClass('hidden');
});
$('.input [type="number"]').on('blur', function(){
var number = Math.round($(this).val() * 100) / 100;
var text = number.toFixed().toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if (number < 0) {
$(this).prev().addClass('negative');
text = "("+text.replace(/-/g,"")+")";
}
if (!number) {text = "-";}
$(this).prev().val(text);
$(this).prev().removeClass();
$(this).addClass('hidden');
});
});
Fiddle. It will work if you take it out of the if
statement, so the issue seems to be that $(this)
is not making its way into the if
statement. (Edit: Seems my assumption about this was incorrect. See the comments below.) These two similar questions made use of .filter
to resolve this issue, but I couldn't figure out how to make that work with the code above.
So how do I get this to work?