简体   繁体   中英

How to check if someone has added 4 letters or more on input type text?

With this script bellow made a ajax call to my file veriUSPF.php in this file i have a SELECT query to check if the username is available. This script bellow is executed onBlur , but i want it to execute the ajax call only if someone added 4 letters or more on the input, is this possible?

html:

<input id="UsName" type="text" minlength="4" maxlength="17" autocomplete="off" onBlur="checkAvailability()" value="<?php echo htmlentities($username, \ENT_QUOTES, 'UTF-8', false); ?>" name="changeUsernamePF">
<span id="user-availability-status"></span>

script:

function checkAvailability() {
    jQuery.ajax({
        url: siteURL + "/veriUSPF.php",
        data: "changeUsernamePF=" + $("#UsName").val(),
        type: "POST",
        success: function(a) {
            $("#user-availability-status").html(a)
        }
    })
}

You may use input event:

 $('#UsName').on('input', function(e) { if (this.value.length>=4) { console.log('call ajax now'); } }).trigger('input'); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="UsName" type="text" minlength="4" maxlength="17" autocomplete="off" onBlur="checkAvailability()" value="" name="changeUsernamePF"> <span id="user-availability-status"></span> 

Using an inline event you can write:

 function checkAvailability(e, ele) { if (ele.value.length>=4) { console.log('call ajax now'); } } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="UsName" type="text" minlength="4" maxlength="17" autocomplete="off" oninput="checkAvailability(event, this)" value="" name="changeUsernamePF"> <span id="user-availability-status"></span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM