Unable to type floating point values in text box with javascript conversion

Viewed 113

In the below code I need to set a minus number for the text even when the user types a positive value. That is working fine.

However it doesn't allow me to enter a floating-point value. When I try to enter the decimal point from the keyboard it will not allow it. That is because I am taking the absolute value.

Does anyone know how to figure this out? A user should be able to enter a floating-point value as well such as 34.50. Where have I gone wrong and how should I correct this?

$('#loss').bind("keyup blur", function() {
  var a = Math.abs(Number($(this).val()));
  var c = a * -1;
  $('#loss').val(c);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="loss" type="text" placeholder="type" style="border: none; text-align: center;" class="amt_num_box_reduce_space">

2 Answers

I agree with Rory's comment on your question and what you're wishing to do might be bad practice but if you insist, here's a solution.

When you convert your value to a Number, your . will be removed because it's considered a string since there's no number after it.

The code below checks if a period has been added at the end and if so adds it when setting the value again.

Now keep it mind that you will run into problems if the user enters letters, a second period etc. The code will return NaN and the user will have to select all the text and replaceit because the backspace key won't work either. But this problem is present in your original code also.

$('#loss').bind("keyup blur", function() {
  var t = $(this);
  var value = t.val();
  var lastCharacter = value.substring(value.length-1);
  var hasPeriod = false;
  if (lastCharacter === '.') {
   hasPeriod = true;
  } 
 
  var a = Math.abs(Number(value));
  var c = a * -1;
  
  t.val(c + (hasPeriod ? '.' : ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="loss" type="text" placeholder="type" style="border: none; text-align: center;" class="amt_num_box_reduce_space">

You'd have less problems if you removed your validation on keyup and just use blur but again, setting a "minus" in front of the input field and converting it when necessary would be the ideal solution.

The problem here lays in Javascript type conversion. When you enter decimal point a String value "10." gets converted to number 10 and later you overwrite entered value with a string "10" with decimal point lost.

There can be number of approaches to solve this problem, you may add minus sign when input control lose his focus, but I would recommend to use so called "Input Adornments" to indicate that this field stores negative number and actually negate the number during form processing.

Related