Francisunoxx Francisunoxx - 4 months ago 8
jQuery Question

Checking table data if has input

I'm trying to check my table data for empty field. I used

$('td:has(input)')
because all of my cell has
<input type="text" class="form-control">
. What I want to do if the user hit the Save button it will checked if all the textfield is empty otherwise it will prompt a message. But the user can fill one of the textfields but cannot be left blank. How can I achieve this?

Table:

<div class = "col-md-12">

<table class = "table" id = "customFields">

<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th class = "description">Description</th>
<th>Quantity</th>
</tr>
</thead>

<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>

</table>

<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
<button type = "submit" class = "btn btn-primary" id = "save">Save</button>

</div>


Script:

<script>

$(document).ready(function ()
{
$("#addMore").click(function ()
{
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});

$("#removeRow").click(function()
{
if ($('#customFields tbody tr').length== 1)
{

alert('Cannot be left blank');
}
else
{
$('#customFields tr:last').remove();
}

});

$("#save").click(function ())
{

if ($('td:has(input)').text(function ()
{

}));

});

});


</script>

Answer

You could loop through all elements with the form-control class and make sure their combined values length is greater than zero.

$("#save").click(function (){
    var values = "";
    $.each($(".form-control"), function(i, c){
        values = values + $(c).val().trim(); // .trim() to remove white-space
    });
    if(values.length > 0)
    {
        //Success!
    }
    else
    {
        // Error!  
    }
});
Comments