0

I just allow someone to enter data in the form of numbers. If the data entered in the form of a mixture, the numbers and text, the text will be deleted.

However, I use jQuery which is not true. It turns out that removed precisely both the numbers and text.

The following code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

<div id="test">0123456789text</div>

<script>
if ($('#test').html()!="0123456789"){
$('#test').remove();
}
</script>

How do I fix it?

Note: I do not have access to edit the <input> or <textarea> on the form

Kangsigit
  • 54
  • 6
  • 2
    Possible duplicate of [HTML Text Input allow only Numeric input](http://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input) – But those new buttons though.. Jan 25 '16 at 16:10
  • @Billy - Sorry, this is another story. I was the blogger.com If someone sends you comments, then I can not edit the part you are looking for. – Kangsigit Jan 25 '16 at 16:14
  • well in that case it's a dupe of http://stackoverflow.com/questions/1862130/strip-non-numeric-characters-from-string. either way it's a dupe and this question has been asked a thousand times. – But those new buttons though.. Jan 25 '16 at 16:53

3 Answers3

1

Your current solution is testing to see if the input matches the exact string 0123456789, and if not removes the entire string.

To remove only the characters (and leave the numbers) you can use a regular expression.

var regex = /[a-z]*/ig;
var input = $('#test').html();

var cleanedInput = input.replace(regex,'');

Here's what this code is doing:

  1. The regex matches any characters, lower or uppercase.
  2. Grab the string you want to clean from your input.
  3. Use .replace() to replace any matched characters with an empty string.
  4. cleanedInput contains the cleaned string for later use.
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
0

The next code to check for alphabet letters

var str = $('#test').text().trim();
if (str.match(/[a-z]/i)) {
    // alphabet letters found
    $('#test').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">0123456789text</div>
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
0

Another way to remove all is not a number is:

  var obj = $('#test');
  obj.text(obj.text().replace( /[^\d]/g ,''));

gaetanoM
  • 41,594
  • 6
  • 42
  • 61