Reputation: 515
I've seen this question asked a few times (here for example), and despite my best attempts to replicate, and reading up on regex, this doesn't seem to work:
$("#button").click(function () {
new_number = $("#the_input").val();
new_number = new_number.replace(/[^0-9]+/g, '')
// also doesn't work: (/\D/g, '')
$("#result").html(new_number);
});
The Goal: On button click, collect value from input, remove NON-NUMBERS and output string inside a div.
The Result: When I put a number in, it comes out fine. When I put a NON-NUMBER & a NUMBER, or anything but a number it comes out blank. It seems to replace the whole string, and not just the matched characters.
Help?
Upvotes: 0
Views: 169
Reputation: 12402
The reason this doesn't work is that you are using a a type="number"
input
. The standard requires the value
in a number
input to be a floating-point number. If a non-floating point value is entered when you query .value
the browser returns an empty string. In Firefox if you query .value
and it has an invalid value the input will be given a red glow around it indicating that it is an invalid value, at present, other browsers I tested do not; they just fail silently.
This means that when the browser evaluates new_number.replace(/[^0-9]+/g, '')
it is actually evaluating ''.replace(/[^0-9]+/g, '')
, which results in an empty string.
As the previous answer suggested you could fix this behavior by changing it to a normal text
input.
Alternatively, instead of trying to sanitize the input with a regular expression, you could validate the field by checking if .val()
returns an empty string and warning the user if it did:
$("#button").click(function () {
var new_number = $("#the_input").val(); // don't forget to use var or your variable will be an implicit global!
if (new_number === '') {
// warn the user here
} else {
$("#result").html(new_number);
}
});
When troubleshooting things like this, checking to make sure the input was what you were expecting can save you a lot of headaches!
Upvotes: 1
Reputation: 1094
Use this code to filter it:
String.prototype.filter = function(){
return this.match(/([0-9])/g).join("");
};
Example:
$("#button").click(function(){
new_number = $("#the_input").val().filter();
$("#result").html(new_number);
});
Upvotes: -1
Reputation: 388316
If you want to allow non numerical values to be entered into the input field, change the type to text
from number
<input type="text" id="the_input">
Demo: Fiddle
Upvotes: 7