Fin
Fin

Reputation: 353

Remove all letters from input value

I want to make a button that clears an input type='text' from all its letters. I want it to, when clicked, remove all characters except numbers and commas.

<input type="text" id="txt" value="1a,2b,3c">
<input type="button" id="reml" value="Remove Letters" onclick="???????">

I was thinking 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 that'd work...

Any ideas?

Upvotes: 3

Views: 5618

Answers (4)

shizhz
shizhz

Reputation: 12501

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>

Upvotes: 0

Escualo
Escualo

Reputation: 42072

You could use a function like the following one to transform the text:

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

Upvotes: 0

E. Sundin
E. Sundin

Reputation: 4181

Something along these lines.

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

Upvotes: 5

Jerfov2
Jerfov2

Reputation: 5504

Make this the onclick code:

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

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

Upvotes: 1

Related Questions