jQuery code to check if all textboxes are empty

Find jQuery code to check if all the input type 'text' element or textboxes are empty or not. This is quite useful for validation. This jQuery code loops through all the textboxes and check their value. If value is empty then it adds a red color border to let user know that this field is required.

$(document).ready(function() {
    $('#btnSubmit').click(function(e) {
        var isValid = true;
        $('input[type="text"]').each(function() {
            if ($.trim($(this).val()) == '') {
                isValid = false;
                $(this).css({
                    "border": "1px solid red",
                    "background": "#FFCECE"
                });
            }
            else {
                $(this).css({
                    "border": "",
                    "background": ""
                });
            }
        });
        if (isValid == false) 
            e.preventDefault();
        else 
            alert('Thank you for submitting');
    });
});?

See result below

See Complete Code

As you can see that in above demo, all the textboxes are validated but what if when you want to validate only some of them, not all. For example, from above demo you only want to validate all the fields excluding "Age".

So to achieve this, assign a css class to all textboxes which needs to be validated and change selectors to select only those textbox which have that class.

$('input[type="text"].required').each(function() {
});

See Complete Code

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



Responsive Menu
Add more content here...