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 mas.
<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?
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 mas.
<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?
Share Improve this question asked Mar 21, 2017 at 1:43 FinFin 3533 gold badges6 silver badges17 bronze badges 2- 2 Create a jsFiddle with a targeted example. jsfiddle/sheriffderek/f6r71z7o It looks like you know you need to use regex, so outline what you've tried and what you think the issue may be a bit more clearly. – sheriffderek Commented Mar 21, 2017 at 1:45
- "But I'm not sure if something like that'd work..." - So actually trying it was more trouble than posting here? – nnnnnn Commented Mar 21, 2017 at 2:11
4 Answers
Reset to default 5Something 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()">
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 ma characters and replaces them with an empty string
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;
};
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./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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744114992a4559129.html
评论列表(0条)