Last Updated on August 28, 2022 by Roshan Parihar
In this tutorial, learn how to detect click outside of an input box element using jQuery. The short answer is to use the blur()
event of jQuery to find if the user fills the input box and clicks outside.
You can also use the focusout()
to detect the click when the user clicks outside of the text box element. It’s useful to validate an input box when users fill it and try to leave it without giving the required value.
Let’s find out the different examples given below to perform this task.
Method 1: How to Detect Click Outside Text Box Element Using blur()
To detect the click event outside of the text box element, you have to use the blur()
function of jQuery. Let’s validate an input box to find out if the user enters a valid GST number. See the example to learn the useful method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script> $(document).ready(function(){ $("input").blur(function() { var inputvalues = $(this).val(); var reggst = '/^([0-9]){2}([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}([0-9]){1}([a-zA-Z]){1}([0-9]){1}?$/'; if((!reggst.test(inputvalues)) && (inputvalues!='')){ alert('GST is not valid. It should be in the format "11AAAAA1111Z1A1"'); }else if(inputvalues == ''){ alert("Please fill the details"); }else{ alert("Its a valid GST number"); } }); }); </script> <input type="text" id="mytxt" MaxLength="15" placeholder="Enter your GST number"> |
Output
Enter GST number and click outside to validate
When you fill the above input box and click outside of it, the above script verifies the GST number to find if the entered data is the valid GST number. The GST number is in the format ’11AAAAA1111Z1A1′.
Method 2: Using focusout()
Function to Find Outer Textbox Clicked Event
If you want to find when the users fill the text box and click the outside, you can also use the focusout()
function of jQuery. It gives the same result and detect the same event given in the above example.
Let’s validate an email address to find it the user entered an email in the correct format on click outside. See the example given below to get the idea of using the method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script> $(document).ready(function(){ $( "input" ).focusout(function() { var inputvalue = $(this).val(); var regemail = '/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/'; if((!regemail.test(inputvalue)) && (inputvalue!='')){ }else if(inputvalue == ''){ alert("Please fill the details"); }else{ alert("Its a valid email address"); } }); }); </script> <input type="text" id="mytxt1" placeholder="Enter your email address"> |
Output
Enter email address and click outside to validate
The above example contains the input box. When you fill it in and click outside, it validates the data if a valid email address. If the entered data is in the format ’[email protected]’, then you will get an alert message that it is a valid email address.
You May Also Like to Read