-1

As the title say I've written a small code piece to detect if the entered character is a number or a letter and below is the script code.

function checkNum(i) {

    //language=JSRegexp
    var txt = i.value;

    if (isNaN(txt)){
        document.getElementById("msg").innerHTML = "Numbers only";
        return false
    }else{
        return true
    }

}
      <label for="volume">Volume:</label>
         <input type="text" name="volume" id="volume" size="4" onkeyup="checkNum(this)" style="margin-left:23px;">
      <label for="noPl" style="margin-left: 35px;">No. of Product Lines:</label>
          <input type="text" name="noPl" id="noPl" size="4" onkeyup="checkNum(this)">

 <div id="msg"></div>

I tried to refine this more but when I change this it stops working for some reason.

What I want this to do is not only prompt the message but also to clear out any entered character from the text box and only allow to enter number.

At the current state it's only prompting the user not to enter letters. I did try many other mentioned methods here but none of them were successful until this.

So if can please enlighten me on what to do also keep in mind I'm still learning JavaScripting not pro yet.

Rob
  • 11,492
  • 14
  • 59
  • 94
S4NDM4N
  • 904
  • 2
  • 11
  • 26
  • 1
    Can you not just use the input type `number`? – George Apr 06 '17 at 09:27
  • 2
    Please search first before asking – mplungjan Apr 06 '17 at 09:28
  • I did none of the searched query's were able to give me an idea on what I wanted to do that's why I asked and it get marked as an duplicate nice. – S4NDM4N Apr 06 '17 at 09:48
  • Apologies if you could not find an answer that matched your issue. I do suggest you tell us what makes your issue different. If I apply the first answer from the duplicate to your code: `function isNumber(evt) { evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { document.getElementById("msg").innerHTML = "Numbers only"; return false; } document.getElementById("msg").innerHTML = ""; return true; }` – mplungjan May 02 '17 at 05:43

2 Answers2

1

$(function() {
  $('#staticParent').on('keydown', '#child', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110,190])||/65|67|86|88/.test(e.keyCode)&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="staticParent">
 <input id="child" type="textarea" />
</div>
Sarika Koli
  • 773
  • 6
  • 11
1

You can check

if( typeof txt == 'number' || typeof txt == 'string') {}
MegaMind
  • 653
  • 6
  • 31