0

I am using a ternary operator to check whether user input is a number or not. However, when I press the check button, no matter if I input a number or a letter, an alert display "please enter a number is displayed". Here is my code.

<label style = "font-size:40px">Please Enter A Number Here: </label><input type = "text" id = "num" style = "font-size:40px">
        <button type = "button" onclick = "check()">Check</button>
        <script>
        function check() { 
        var input = document.getElementById("num");
        var check = /^[0-9]*$/;
        (!check.test(input)) ? window.alert("You have only entered numeric characters! Please proceed to press one of the other buttons.") : window.alert("Please enter only numbers!")
        }
        </script>
A B
  • 47
  • 1
  • 5
  • 3
    *input* is a reference to the element, not its value. Use: `var input = document.getElementById("num").value`. Also consider: `alert(check.test(input)?'Only numbers':'Other stuff')` – RobG Jun 15 '16 at 02:18
  • Why use a ternary operator when you do not return anything? Better to use a ternary operator to return the string, than alert that string. – epascarello Jun 15 '16 at 02:20
  • Thank you. The program works now – A B Jun 15 '16 at 02:21
  • Note that since html5 you can use only html attributes to check this kind of things, no need to use javascript: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input – Casimir et Hippolyte Jun 15 '16 at 02:25
  • A link [here](http://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input) might turn out useful. – Wiktor Stribiżew Jun 15 '16 at 05:52

0 Answers0