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()">
      

Run codeHide result


+3


source


Make the code onclick

:

var theinput = document.getElementById('reml')
theinput.value = theinput.value.replace(/[^\d,]/g,'')

      



This uses a regex to find all asymmetric and comma characters and replaces them with an empty string

0


source


To convert text, you can use the following function:

function transform(s) {
    var out = "";
    for (var index = 0; index < s.length; ++index) {
        if ((!isNaN(s[index])) || (s[index] === ',')) {
            out += s[index];
        }
    }
    return out;
};

      

0


source


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>
      

Run codeHide result


0


source







All Articles