JavaScripts Tutorials

104 21

    The Function

    • The basic call to Javascript is through a function. Functions in Javascript are similar to those in other coding languages. The functions are called from the HTML elements in the web page. A function has the basic syntax of the following:

      function myFunction(form)
      {

      }

      Javascript uses brackets just like other familiar languages, such as C++ or C#. The "function" keyword is used to identify the name of the function, which is "myFunction" in this example. The "form" keyword in this example is used as a function parameter. It's standard in Javascript to use the form as a method of manipulating form elements and creating variables associated with the web page.

    Coding Javascript

    • The meat of a function is within the brackets. Javascript has specific syntax when defining variables and manipulating form elements on the web page. Some people have several Javascript functions in a web application, so they choose to create a separate file called a JS file for its extension. The following code displays a pop-up when the user leaves the first_name textbox empty:

      function myFunction(form)
      {
      if (form.first_name.value == '')
      {
      alert('Please enter a first name.');
      }
      }

      The "if" statement is a keyword that is used to create logic flow in the application. If the statement in the parenthesis evaluates to true, then what is within the brackets is executed. In this example, the if statement checks to see if the first_name form textbox is blank. If it evaluates to true, the user is prompted to enter a value into the form element.

    Calling the Element in HTML

    • The last step to creating a Javascript form function is calling it during the submit process. Javascript can be called during the submit process or triggered during other events like clicking a button or hovering over an image. The example below adds the new Javascript function to the form's submit button. The Javascript code will execute before the form is processed on the server.

      <form action="processme.asp" method="post">
      <input type="text" name="first_name">
      <input type="submit" onSubmit="javascript: myFunction(this)">
      </form>

      Notice the onSubmit line in the submit button. This tells the web page to process the Javascript function "myFunction" before submitting the form. This is when the first_name textbox is evaluated and checked for input.

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.