Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot remove commas from input type number value

I'm trying to remove the commas from an input value using JS / jQuery.

The input type is number and I'm running the sanitisation process on key up.

The below code works fine when the input type is text, but not when the input type is number.

I'm using the input type number as a currency input, hence why I'm attempting to remove commas incase someone inputs $1,000 for example.

And I'd like to use input type number as this will mainly be used on mobile devices.

Does anyone know why that might be please?

-

http://codepen.io/anon/pen/YXvxxK

$('.form input').on('keyup', function() {
  field1 = $('#field1').val();
  var newField1 = parseFloat(field1.replace(/,/g, ''));
  console.log(newField1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form">
  <input type="number" id="field1" />
</form>
like image 575
Oliver Evans Avatar asked Jul 14 '15 13:07

Oliver Evans


1 Answers

The problem here isn't that you can't remove the commas, it's that commas aren't valid* within input elements whose type is number.

If we enter "1,234" into the field within your code snippet and hit Return, we're greeted with the following validation error:

Example

This happens because the value "1,234" is deemed invalid. As this is invalid, the element's value will return as an empty string instead of the string value "1,234".

parseFloat("".replace(/,/g, '')) returns NaN.

A quick fix to this is to stop using the number input type and use text instead. However that may not be what you desire. Another way would be to detect whether the value is empty ("") and present the user with a validation failure message.


* It's important to note that this is implementation-specific. The HTML5 specification states that browser vendors are "encouraged to consider what would best serve their users' needs". Treating a comma here as invalid is part of that consideration.

like image 87
James Donnelly Avatar answered Nov 05 '22 07:11

James Donnelly