How to clear textbox value using jQuery

In this short post, I will show you simple jQuery code to clear textbox value. The reason for writing this post is because I have seen many beginner programmers using val() == '', which is wrong as val() is a method that takes argument. It is not a property or attribute. You can call this code on click of button or any other event.

Clear all textbox

$(document).ready(function() {
    $('input[type=text]').each(function() {
        $(this).val('');
    });
});?

Clear single textbox value

$(document).ready(function() {
   $('#txtID').val(''); //txtID is textbox ID
});?

Clear textbox value onfocus

$(document).ready(function() {
    $('#txtID').focus(function() {
        $(this).val('');
    });
});?

Associate focus event with every textbox

$(document).ready(function() {
    $('input[type=text]').focus(function() {
        $(this).val('');
    });
});?

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...