Thursday, 28 February 2013

jQuery: Coding



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
1
$(document).ready(function() {
2
    $('input[type=text]').each(function() {

3
        $(this).val('');
4
    });

5
});
Clear single textbox value
1
$(document).ready(function() {
2
   $('#txtID').val(''); //txtID is textbox ID

3
});
Clear textbox value onfocus
1
$(document).ready(function() {
2
    $('#txtID').focus(function() {

3
        $(this).val('');
4
    });

5
});
Associate focus event with every textbox
1
$(document).ready(function() {
2
    $('input[type=text]').focus(function() {

3
        $(this).val('');
4
    });

5
});

No comments:

Post a Comment