Hello Friend, When we have input fields in our websites then many custom styling we apply or required for form validation. For example if user entered something, if user changed the value of input, is input empty. Many more depend on user actions.
Here I created one small utility which you can add in your site code and all the inputs of your project can be validated using this, without adding any extra code. Below is the code which you need to add in JavaScript.
function inputValidator(inputSelector) { var current_val = $(inputSelector).val(); function onChange() { $(this).removeClass("dirty").addClass("pristine"); this.updated_val = $(this).val(); if (this.updated_val != current_val) { $(this).removeClass("pristine").addClass("dirty"); } } function onFocus(){ $(this).removeClass("untouched").addClass("touched"); } $(inputSelector).on("input change", onChange); $(inputSelector).on("focus", onFocus); return true; } $(document).ready(function() { $.each($("input"), function(key, value) { new inputValidator(value); }); });
When you add above code in your javascript, then all input will have one class "untouched" by default. Class of input will change on user action, and you can apply style on input based on classes.
- By default class is untouched
- When you touch the input, class will change to "touched"
- When you enter something in the input, class will change to "touched dirty"
- When you revert you changes in the input, class will be "touched pristine"
For example, if our inputs are as shown below:
Text:
Email:
Password:
Number:
Date:
CSS code that I have written for inputs:
.name{ display: inline-block; width:80px; } input.untouched{ background-color: #DDF4FC; } input.touched{ background-color: #6AFAFA; } input.touched.pristine{ background-color: #43FF44; } input.touched.dirty{ background-color: #FF4422; }
Now if user interact with inputs, colors changes as mentioned in css style
Here is the codepen link : http://codepen.io/JitendraPal/pen/MebLoX
No comments:
Post a Comment