Amra
Amra

Reputation: 25180

How can you determine if textboxes inside a table row are empty using jQuery?

I have the following function:

 var emptyFields = false;

 function checkNotEmpty(tblName, columns, className){

    emptyFields = false;

     $("."+className+"").each(function() {
          if($.trim($(this).val()) === "" && $(this).is(":visible")){
             emptyFields = true;
             return false; // break out of the each-loop
          }
     });

      if (emptyFields) {
             alert("Please fill in current row before adding a new one.")
       } else {
              AddRow_OnButtonClick(tblName,columns);
       }
}

Its checking that all elements in the table are not empty before adding a new row, and I only need to check that the last row of the table has at least an element which its not empty and not the whole table.

The className its applied to the table. Please notice, that the problem I have its checking the last row and only one element of the row has to have some text in it. (e.g. each row has 5 textboxes at least one textbox need to have some text inside in order to be able to add another row, otherwise, the alert comes up).

Upvotes: 2

Views: 3057

Answers (3)

John Rasch
John Rasch

Reputation: 63445

This should work:

if ($('.' + className + ' tr:last input:text:visible[value]').length > 0) {
    AddRow_OnButtonClick(tblName,columns);
} 
else {
    alert("Please fill in current row before adding a new one.")
}

This of course assumes the className you're using is used on the table element.

Working example:

<script type="text/javascript">
$(function(){
    $('#btn').click(function(){
        if ($('.test tr:last input:text:visible[value]').length > 0) {
            alert('SUCCESS - at least 1 value is filled in!');
        } 
        else {
            alert("FAIL - all textboxes on last row are empty.")
        }
    });
});
</script>

<table class="test" border="1">
<tr>
<td><input type="text" value="filled" /></td>
<td><input type="text" value="in" /></td>
</tr>
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
</table>

<input id="btn" type="button" value="Click Me!" />

Upvotes: 2

karim79
karim79

Reputation: 342635

There is no need for a loop:

if($("." + className + ":visible[value]").length) {
   // one or more has been filled out, and is visible
   // [value] matches non-empty values only
}

Upvotes: 1

justkt
justkt

Reputation: 14766

Have you considered the :last selector and some children in addition to "."+classname? Something along the lines of $("."+classname+" tr:last td") should check each cell in the last row.

EDIT: Initially suggested last-child, but switching to something that fits the OP's needs better on comment.

Upvotes: 1

Related Questions