Remove all letters from the input value
I want to make a button that clears input type='text'
all its letters. I want all characters except numbers and commas to be removed on click.
<input type="text" id="txt" value="1a,2b,3c">
<input type="button" id="reml" value="Remove Letters" onclick="???????">
I thought it would be something like:
onclick="document.getElementById('reml').value.replace(a[],'');
a = ['a','b','c',etc.];
But I'm not sure if something like this would work ...
Any ideas?
+3
source to share
4 answers
Something like that.
function clearInvalid() {
var input = document.getElementById('txt')
input.value = input.value.replace(/[^\d,]/g,'')
}
<input type="text" id="txt" value="1a,2b,3c">
<input type="button" id="reml" value="Remove Letters" onclick="clearInvalid()">
+3
source to share
You can use regex
to do this and jQuery can make your code even shorter:
<html>
<input type="text" id="txt" value="1a,2b,3c">
<input type="button" id="reml" value="Remove Letters">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("#reml").on("click", function(event) {
$("#txt").val($("#txt").val().replace(/[^\d,]/g, ''));
});
</script>
</html>
0
source to share