Pages

10 Sept 2013

jQuery code to check if all textboxes are empty with jQuery, jQuery Codes, jQuery Tips, jQuery Validation

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');
    });
});​


HTML 

<table>
<tr>
    <td>First Name:
    </td>
    <td><input type='text' id='txtFName'/ >
    </td>
</tr>
<tr>
    <td>Last Name:
    </td>
    <td><input type='text' id='txtLName'/ >
    </td>
</tr>
<tr>
    <td>Age:
    </td>
    <td><input type='text' id='txtAge'/ >
    </td>
</tr>
<tr>
    <td>Email:
    </td>
    <td><input type='text' id='txtEmail'/ >
    </td>
</tr>
<tr>
    <td colspan="2" style='text-align:center;'><input type="button" id="btnSubmit" value=" Submit ">
    </td>
</tr>
</table>

No comments:

Post a Comment