How to Check an Input Integer in JavaScript

JavaScript is a useful language for adding any sort of interactive or dynamic elements to HyperText Markup Language (HTML). While JavaScript has a different syntax than that of HTML, it can be easily integrated or referenced within existing HTML code. In order to verify user input in a website, JavaScript is often extremely useful. You can use JavaScript to check the input for any condition that you desire and create a series of processes to be executed depending on the result.

Things You'll Need

  • Word processing program
Show More

Instructions

    • 1

      Open your HTML code in a word processing program.

    • 2

      Create a function in JavaScript to which you will send the input. This function must go in either the head or body of your HTML code. Make sure to label the function so that it will be easy to remember. For example, consider the code:

      <script language="JavaScript" type="text/javascript">

      function test(){
      }

      </script>

      This creates a function called "test" that can then be called from your HTML.

    • 3

      Modify your HTML form tag to call the JavaScript function. This can be done in a number of ways. One of the most straightforward methods is to use the "onclick" attribute within an input tag:

      <form name="prompt" action="" method="get">
      Number:
      <input type="text" name="input">
      <input type="submit" value="Submit" onclick="javascript:return test();">
      </form>

      In your function, link the variable in the function with the input in the form. For example:

      function test(){
      var input = document.prompt.number.value

      This can also be done by using document.prompt.number.value wherever you wish to call the submitted data. Always make sure that your names within the function are exactly the same as they appear within the form tags (and using the syntax document.formname.inputname.value). Additionally, a variable can be called within the function by assigning the submitted input an ID, and using document.getElementById instead.

    • 4

      Create an "if" statement within your function. Within that "if" statement, check for the desired condition. For example, if you want to check if an input integer is greater than 5, write:

      function test(){
      if (input > 5)
      { ... }

      Within the brackets that follow the "if" clause, enter the actions you wish to have performed if the integer meets the condition. Create additional "if" clauses in the event of multiple conditions. Be sure to also include an "else" clause that describes what to do if the input does not meet the conditions. For example,

      else{
      alert("Your input does not meet the conditions!");
      return false;
      }

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured