Pages

Friday, May 10, 2019

Sharing and Applying multiple Event Handlers – JavaScript / jQuery

This was back when I didn’t use Angular and used jQuery a lot for making my views interactive. A thing that I learned back then was that class can be used to not only share styles but functionality.
Unlike the ‘id’ which is unique to an element, same class name can be shared across multiple elements and helps in reusing styles using CSS. Or at-least that’s the extent to which I used them.
So, here I was creating a form and I realized that along with styles, there was also common functionality. A lot of the fields in the form shared validation logic and when using jQuery I realized that I can simply pass in a class name to the ‘$()’ and I am done!
I can attach the same event handler to all elements which had that class name. Also I can add multiple event handlers to the same element (of-course ensuring that the event handlers are not order dependent).
This simplified the code greatly as I could now add a class name and I would automatically get the relevant styles and the required event handling applied.
Sample Code:

<html>
  <head>
  </head>
  <body>
<form>
      Name: <input type= "Text" class="MustNotBeEmpty"/>
      Account Number: <input type= "Text" class="MustNotBeEmpty MaxSize6" />
    </form>
    <script>
      $(".MustNotBeEmpty").blur(function ()
      {
        if(this.value.length === 0)
        {
          alert("You need to have some value.");
        }
      });
      $(".MaxSize6").blur(function ()
      {
        if(this.value.length > 6)
        {
          alert("Value cannot exceed 6 characters.");
        }
      });          
    </script>
  </body>
</html>

So now when the validation occurs:


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.