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.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..