How can you tell if text boxes 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 there is at least an element in the last row of the table that is not empty and not the whole table .

ClassName applies to the table. Please note that the problem is that I am checking the last line and only one element of the line should have some text in it. (for example, each line has 5 text boxes, at least one text box must have some text inside to be able to add another line, otherwise a warning appears).

+2


a source to share


3 answers


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 usage className

used for the element table

.



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!" />

      

+2


a source


Have you considered : last selector and some children in addition to "."+classname

? Something along the lines $("."+classname+" tr:last td")

should check every cell in the last line.



EDIT: Originally suggested last-child

, but moving on to something the OP fits, better comment.

+1


a source


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
}

      

+1


a source







All Articles