How to find that all input text boxes are empty in table? - javascript

I have a html table with data like
<table>
<tr>
<td>abc</td>
<td>781</td>
<td><input id="barcodedb0" class="hide" type="text" /><input id="barcode0" class="hide" type="text" /></td>
</tr>
<tr>
<td>abc</td>
<td>781</td>
<td><input id="barcodedb0" class="hide" type="text" /><input id="barcode0" class="hide" type="text" /></td>
</tr>
</table>
In JQuery
$('#library_info_tbl tbody').on("keyup", "tr td input:nth-child(2)", function() {
if(all the textboxes are empty)
// do something
});
I am trying to find out how will I check that all text boxes in the table are empty.
Note that text boxes with "hide" class are hidden and are used for other purpose.
Please help!!!

You can use this
This code will work only for second input.
$('#library_info_tbl tbody').on("keyup", "tr td input:nth-child(2)", function() {
var oneEmpty = false;
$("#library_info_tbl tbody tr td input:nth-child(2)").filter(function () {
return $.trim($(this).val()) == '';
});
if(oneEmpty)
// do something
});
This code will work only for all input.
$('#library_info_tbl tbody').on("keyup", "tr td input:nth-child(2)", function() {
if($("#library_info_tbl tbody input:empty").length == $("#library_info_tbl tbody input").length)
{
// do something
}
});
// Instead of $("#library_info_tbl tbody input:empty") you can also use $("input.hide:empty")

Try this
var allempty = true;
$('.hide').each(function(){
if($(this).val()!=''){
allempty = false;
}else{
allempty = true;
}
});
if(allempty) {
//this is empty
}

you can use input[type=text] as selector :
For i.e. :
var emptyValues = 0;
$('table input[type=text]').each(function(){
if($(this).val() != ''){
console.log($(this).val());
emptyValues = 1;
}
});
if(emptyValues == 0){
//enter code here
}

Considering the id of your table is tableId, you could try:
if($("table#tableId input[class!='hide'][value='']").length == $("table#tableId input[class!='hide']").length) {
// do something
}
or simply:
if($("table input[class!='hide'][value='']").length == $("table input[class!='hide']").length) {
// do something
}

You can do it by for loop iteration and check each value
function checkEmpty(){
var elems = $("table input[type=text]");
var isEmpty = false;
for(let i=0 ; i < elems.length;i++){
if($(elems[i]).val().trim() != ''){
isEmpty = true;
break;
}
}
$("#isempty").html(isEmpty?'All Not Empty':'All Empty');
//return isEmpty;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>abc</td>
<td>781</td>
<td><input id="barcodedb0" class="hide" type="text" /><input id="barcode0" class="hide" type="text" /></td>
</tr>
<tr>
<td>abc</td>
<td>781</td>
<td><input id="barcodedb1" class="hide" type="text" /><input id="barcode1" class="hide" type="text" /></td>
</tr>
</table>
<input onclick="checkEmpty()" type="button" value="check empty"/>
<div id="isempty"></div>
Care about duplicate id's

Related

Use index to set value on jquery

Could someone please tell me how I can use the index in this situation?
I have a text field, which is my multiplication factor
<input type="text" id="value">
And I have a table that has 2 fields arranged in the same tr
One with a fixed value
And one that must be the result of multiplying these two values.
Example:
In input I set value = 2
Field Value2 = Value 1 * 2
Value 1
Value 2
3
6
4
8
My jQuery function looks like this:
$( "#btn" ).on( "click", function()
{
let vlUS = $('#value').val()
$("table > tbody > tr > td > input")
.each(function (index) {
let vl1 = $('.val1').val()
let vl2 = vl1 * vlUS
$('.val2').val(vl2)
});
});
Using this way, assigns the same value to all "value2" fields
How can I use index to tune the process?
Loop over the rows and use each row instance to find() the specific inputs within that row
$("#btn").on("click", function() {
let vlUS = $('#value').val();
$("table > tbody > tr").each(function(index) {
const $row = $(this);
let vl1 = $row.find('.val1').val()
let vl2 = vl1 * vlUS
$row.find('.val2').val(vl2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn">
Calculate
</button> US: <input id="value" value="5" />
<table>
<tr>
<td><input type="text" class="val1" value="3"></td>
<td><input type="text" class="val2"></td>
</tr>
<tr>
<td><input type="text" class="val1" value="6"></td>
<td><input type="text" class="val2"></td>
</tr>
</table>
Consider the following code.
$("#btn").on("click", function() {
$("table tbody tr").each(function(index, elem) {
$(".val2", elem).val(parseInt($(".val1", elem).val()) * parseInt($("#value").val()));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn">Calculate</button> US: <input id="value" value="5" />
<table>
<tr>
<td><input type="text" class="val1" value="3"></td>
<td><input type="text" class="val2"></td>
</tr>
<tr>
<td><input type="text" class="val1" value="6"></td>
<td><input type="text" class="val2"></td>
</tr>
</table>
Simply reduces the operation to one line. Also ensures that if the User enters a Letter; it won't fail.

How to check if all textboxes in a row are filled using jquery

I have 3 textboxes in each row. At least one of the rows should be filled completely. All the textboxes in any of the rows should not be empty. I have tried below code, it's for the first row only.
var filledtextboxes= $(".setup_series_form tr:first input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
We want to get the maximum number of non-empty textboxes in any row, TIA.
Loop through all the rows. In each row, get the number of filled boxes. If this is higher than the previous maximum, replace the maximum with this count.
var maxboxes = -1;
var maxrow;
$(".setup_series_form tr").each(function(i) {
var filledtextboxes = $(this).find("input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
if (filledtextboxes > maxboxes) {
maxboxes = filledtextboxes;
maxrow = i;
}
});
You are targeting only first tr here $(".setup_series_form tr:first input:text") so you will not get the expected output.
You have to iterate with every row(tr) inside form and then find the count of
text field having not empty values and store in a maxCount variable by comparing it previous tr count.
Here is a working snippet:
$(document).ready(function() {
var maxCountInRow =0;
var rowNumber;
$(".setup_series_form tr").each(function(index){
var filledtextboxes= $(this).find("input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
if(filledtextboxes>maxCountInRow){
maxCountInRow=filledtextboxes;
rowNumber=index;
}
});
console.log("Row Number:"+rowNumber+" having maxCount: "+maxCountInRow);
});
.registrant_table{width: 100%;border: 1px solid #ccc;text-align: center;}
.registrant_table tr td{border: 1px solid #ccc;height: 42px;font-weight: bolder;}
.registrant_table input{border: 0px !important;width: 100%;height: 42px;text-align: center;font-weight: normal;}
label.error{color: red !important;}
.err-fields{background-color:red;color: white !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="setup_series_form">
<div>
<table class="registrant_table">
<tr class="title">
<td>No</td>
<td>Official Full Name</td>
<td>Mobile Contact</td>
<td>Email</td>
</tr>
<tr class="in-fields">
<td>1</td>
<td><input type="text" value="sas" name="firstname[]"></td>
<td><input type="text" value="" name="phone[]"></td>
<td><input type="text" value="" name="email[]"></td>
</tr>
<tr class="in-fields">
<td>2</td>
<td><input type="text" value="sas" name="firstname[]"></td>
<td><input type="text" value="sas" name="phone[]"></td>
<td><input type="text" name="email[]"></td>
</tr>
<tr class="in-fields">
<td>3</td>
<td><input type="text" name="firstname[]"></td>
<td><input type="text" name="phone[]"></td>
<td><input type="text" name="email[]"></td>
</tr>
</table>
</div>
</form>

jQuery validate input fields in table cells

I'm trying to validate inputs in a table.
I have a table with rows and in their inputs. If some of the input is not empty, We need to check whether the adjacent input has value, if not return false. If both are empty true.
I made a little demo of what I want to do.
https://jsfiddle.net/51bz8ggv/2/
$(document).ready(function() {
$("table tr :input").each(function () {
console.log(this.value);
// some check here
});
});
Thanks.
https://jsfiddle.net/51bz8ggv/3/
$(document).ready(function() {
$("table td:nth-child(1) :input").each(function(index) {
var rowDate = $(this).val()
var rowPoints = $("table td:nth-child(2) :input").eq(index).val()
if (rowDate === "" && rowPoints === "") {
//both are empty
console.log(index + " : true")
} else if (rowDate !== "" && rowPoints !== "") {
//both have values
console.log(index + " : true")
} else {
//one is empty and the other have value
console.log(index + " : false")
}
});
});
I'm using nth-child(1) to loop through the first column than compare the value with the input in nth-child(2) aka the 2nd column. so if you work with different table be sure to adjust these numbers to fit the columns you're comparing
Iterate over the tr and compare the total input element with empty input field count.
// get all tr except the first and iterate over them
$("table tr:nth-child(n+2)").each(function() {
// get all input fields within it
var $inp = $(':input', this);
// filter out all empty input fields
var $fil = $inp.filter(function() {
return $(this).val().trim() == '';
});
// now check all are non-empty or all are empty
console.log($fil.length == 0 || $fil.length == $inp.length);
});
$("table tr:nth-child(n+2)").each(function() {
var $inp = $(':input', this);
var $fil = $inp.filter(function() {
return $(this).val().trim() == '';
});
console.log($fil.length == 0 || $fil.length == $inp.length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%" border="1">
<tr>
<th>Date</th>
<th>Points</th>
<th>Result</th>
</tr>
<tr>
<td>
<input type="text" name="date[]" class="date" value="2016-09-02" />
</td>
<td>
<input type="text" name="points[]" class="points" />
</td>
<td>false(error)</td>
</tr>
<tr>
<td>
<input type="text" name="date[]" class="date" />
</td>
<td>
<input type="text" name="points[]" class="points" value="679" />
</td>
<td>false(error)</td>
</tr>
<tr>
<td>
<input type="text" name="date[]" class="date" value="2016-09-02" />
</td>
<td>
<input type="text" name="points[]" class="points" value="679" />
</td>
<td>true</td>
</tr>
<tr>
<td>
<input type="text" name="date[]" class="date" />
</td>
<td>
<input type="text" name="points[]" class="points" />
</td>
<td>true</td>
</tr>
</table>
This could be helpful.
$(document).ready(function() {
$("table tr").each(function () {
$inputarray = $(this).find("input");
$length = $inputarray.size();
if($length>0){
$i = 0;
$inputarray.each(function() {
if(this.value!=="") {
$i++;
}
});
if($i===0 || $i===$length){
$(this).find( "td:last" ).text("true");
} else {
$(this).find( "td:last" ).text("false");
}
}
});
});
Your updated Fiddle
Try this code:
$(document).ready(function() {
$(".date").each(function () {
var $that = $(this);
var $currentRow = $that.parents("tr");
var $points = $currentRow.find(".points");
console.log($that.val() )
console.log($points.val() )
var $currentROw = $currentRow.find("td:last-child").text(($that.val() == "" && $points.val() == "") || ($that.val() != "" && $points.val() != ""));
});
});
https://jsfiddle.net/oa42nzr0/

Search table contents using javascript

I am currently working on javascript. In this code I have a table and a textbox. When I enter data in the textbox it should show the particular value that I typed but it doesn't search any data from the table. How do I search data in the table?
Here's a jsfiddle http://jsfiddle.net/SuRWn/
HTML:
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr>
<th> </th>
<th> </th>
<th><center> <b>COURSE CODE</b></center></th>
<th><center>COURSE NAME</center></th>
</tr>
</thead>
<tbody>
<tr id="rowUpdate" class="TableHeaderFooter">
<td >
<center> <input type="text" name="input" value="course" ></center>
<center> <input type="text" name="input" value="course1" ></center>
<center> <input type="text" name="input" value="course2" ></center>
</td>
<td>
<center> <input type="text" name="input" value="subject" ></center>
<center> <input type="text" name="input" value="subject1" ></center>
<center> <input type="text" name="input" value="subject2" ></center>
</td>
</tr>
</tbody>
</table >
<form action="#" method="get" onSubmit="return false;">
<label for="q">Search Here:</label><input type="text" size="30" name="q" id="q" value="" onKeyUp="doSearch();" />
</form>
Javascript:
<script type="text/javascript">
//<!--
function doSearch() {
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for ( var i = 0; i < rows.length; i++ ) {
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
if ( fullname ) {
if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
}
//-->
</script>
checking with chrome console, it seems that innerHtml for the 'fullname' is returning an error:
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
That's because the first tr tag you have is in the thead and it doesn't have any td at all. Changing the start of your loop to 1 will fix that:
for ( var i = 1; i < rows.length; i++ ) { //... and so on
yuvi is correct in his answer. I've incorporated this in a fiddle - http://jsfiddle.net/dBs7d/8/ - that also contains the following changes:
Inputs with course and subject grouped into individual rows.
td tags align underneath th tags.
Code refactored to improve readability.
Instead of checking the html of the td tags I've changed it to check the value attribute of the input tags. This means you can change the value of the input and still search.
I also changed the style alteration to use backgroundColor. This can easily be reverted to display.
See this link.
HTML:
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr>
<th>Course</th>
<th>Subject</th>
<th>COURSE CODE</th>
<th>COURSE NAME</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="course" /></td>
<td><input type="text" value="subject" /></td>
</tr>
<tr>
<td><input type="text" value="course1" /></td>
<td><input type="text" value="subject1" /></td>
</tr>
<tr>
<td><input type="text" value="course2" /></td>
<td><input type="text" value="subject2" /></td>
</tr>
</tbody>
</table>
Search here (with jQuery):<input type="text" size="30" value="" onKeyUp="doSearchJQ(this);" /><br />
Search here:<input type="text" size="30" value="" onKeyUp="doSearch(this);" />
Javascript:
function doSearchJQ(input) {
var value = $(input).val();
if (value.length > 0) {
$("#results tbody tr").css("display", "none");
$('#results input[value^="' + value + '"]').parent().parent().css("display", "table-row");
} else {
$("#results tbody tr").css("display", "table-row");
}
}
function doSearch(input){
var value = input.value;
var table = document.getElementById('results');
var tbody = table.querySelector("tbody");
var rows = tbody.querySelectorAll("tr");
var visible, row, tds, j, td, input;
for (var i = 0; i < rows.length; i++) {
visible = false;
row = rows[i];
tds = row.querySelectorAll("td");
for (j = 0; j < tds.length; j++) {
td = tds[j];
input = td.querySelector("input");
console.log(input.value.indexOf(value));
if (input.value.indexOf(value) > -1) {
visible = true;
break;
}
}
if (visible) {
row.style.display = "table-row";
} else {
row.style.display = "none";
}
}
}
With jquery it's more compact function. But you can use clear javascript doSearch.
Why don't you use JQuery DataTables? The plugin has a really nice table view as well as automatically enabled search textbox, and should fit in easily with your JavaScript/PHP solution.
See example table below:
The plugin is well-documented, and widely used. It should be very easy to drop in into an existing application, and style it accordingly.
Hope this helps!

jQuery not working on added rows [duplicate]

This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Closed 9 years ago.
I have a table to allow user to do multiple stock entry
<table class="table1" id="table1">
<thread>
<tr>
<th scope="col">Item Name</th>
<th scope="col">Qty</th>
<th scope="col">Rate</th>
<th scope="col">Amount</th>
</tr>
</thread>
<tbody>
<tr>
<td><input type="text"/></td>
<td><input type="text" class="num" id="qty"/></td>
<td><input type="text" class="num" id="rate"/></td>
<td><input type="text" class="num" id="amt"/></td>
</tr>
</tbody>
</table>
<a id="add"><button>Add</button></a>
And this code is to add a new row:
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
var newrow = $("<tr><td><input type="text"/></td><td><input type=\"text\" id=\"qty\"/></td><td><input type="\text\" id="\rate\"/></td><td><input type="\text\" id="\amt\"/></td></tr>");
newrow.insertAfter('#table1 tbody>tr:last');
return false;
});
$(".num").keyup(function() {
var id = $(this).attr('id');
if (id == 'qty') {
var i = parseFloat($("#rate").val())
if (!isNaN(i)) {
var t = ($(this).val()*$("#rate").val());
$("#amt").val(t.toFixed(2));
} else {
$("#amt").val('');
}
} else if (id == 'rate') {
var i = parseFloat($("#qty").val())
if (!isNaN(i)) {
var t = ($(this).val()*$("#qty").val());
$("#amt").val(t.toFixed(2));
} else {
$("#amt").val('');
}
}
});
});
The calculation is working perfect on the first row of table, but when I am adding a second row the calculation is not working. Where I am wrong?
Use event delegation:
$('body').on('keyup', ".num", function() {
// your code
});
Also you must add class .num to your created elements,
and you can't have the same ID for multiple elements, instead
use another attribute (like data-id, it doesn't matter),
var newrow = $('<tr><td><input type="text" /></td><td><input type="text" class="num" data-id="qty"/></td><td><input type="text" data-id="rate"/></td><td><input type="text" class="num" data-id="amt" /></td></tr>');
And in your function get them with this attribute:
$('body').on('keyup', ".num", function() {
var $row = $(this).closest('tr');
var $amt = $row.find('[data-id="amt"]');
var $qty = $row.find('[data-id="qty"]');
var $rate = $row.find('[data-id="rate"]');
var id = $(this).attr('data-id');
if (id == 'qty') {
// now using `$rate` instead of $('#rate')
var i = parseFloat($rate.val())
// other code
}
// other code
});
Give the new rows the num class (your new inputs don't have it), and use .on:
$(document).on('keyup', '.num', function() {
});
This is required if you want to add an event listener to elements that are not yet in the DOM.
Also, element IDs should be unique. Your new inputs are getting the same ID as the previous row.
try this
<table class="table1" id="table1">
<thread>
<tr>
<th scope="col">Item Name</th>
<th scope="col">Qty</th>
<th scope="col">Rate</th>
<th scope="col">Amount</th>
</tr>
</thread>
<tbody>
<tr>
<td>
<input type="text" />
</td>
<td>
<input type="text" class="num" name="qty" id="qty" />
</td>
<td>
<input type="text" class="num" id="rate" name="rate" />
</td>
<td>
<input type="text" class="num" id="amt" name="amt" />
</td>
</tr>
</tbody>
</table>
<a id="add">
<button>
Add</button></a>
<script type="text/javascript">
$(document).ready(function () {
$("#add").click(function () {
var newrow = $('<tr><td><input type="text"></td><td><input type="text" id="qty" name="qty" class="num"></td><td><input type="text" id="rate" name="rate" class="num"></td><td><input type="text" id="amt" name="amt" class="num"></td></tr>');
newrow.insertAfter('#table1 tbody>tr:last');
$('#table1 tbody>tr:last').find('[name="qty"]').keyup(function () {
var this_tr = $(this).closest('tr');
;
var i = parseFloat(this_tr.find('[name="rate"]').val())
if (!isNaN(i)) {
var t = ($(this).val() * this_tr.find('[name="rate"]').val());
this_tr.find('[name="amt"]').val(t.toFixed(2));
} else {
this_tr.find('[name="amt"]').val('');
}
});
$('#table1 tbody>tr:last').find('[name="rate"]').keyup(function () {
var this_tr = $(this).closest('tr');
;
var i = parseFloat(this_tr.find('[name="qty"]').val())
if (!isNaN(i)) {
var t = ($(this).val() * this_tr.find('[name="qty"]').val());
this_tr.find('[name="amt"]').val(t.toFixed(2));
} else {
this_tr.find('[name="amt"]').val('');
}
});
return false;
});
$('[name="qty"]').keyup(function () {
var this_tr = $(this).closest('tr');
;
var i = parseFloat(this_tr.find('[name="rate"]').val())
if (!isNaN(i)) {
var t = ($(this).val() * this_tr.find('[name="rate"]').val());
this_tr.find('[name="amt"]').val(t.toFixed(2));
} else {
this_tr.find('[name="amt"]').val('');
}
});
$('[name="rate"]').keyup(function () {
var this_tr = $(this).closest('tr');
;
var i = parseFloat(this_tr.find('[name="qty"]').val())
if (!isNaN(i)) {
var t = ($(this).val() * this_tr.find('[name="qty"]').val());
this_tr.find('[name="amt"]').val(t.toFixed(2));
} else {
this_tr.find('[name="amt"]').val('');
}
});
});
</script>
This issue can be solved via event delegation to the existing closet parent like in your case is $('#table1') or $(document) which is the parent of all the elements on a page, so you need to change this:
$(".num").keyup(function() {
to this:
$("#table").on('keyup', '.num', function() {
I just seen your additions you are adding same ids when clicked to add, so that results in a invalid html markup due to ids should be unique in the same page (same ids for multiple elems is invalid).
var newrow = $("<tr><td><input type='text'/></td>"+
"<td><input type='text' id='qty'/></td>"+
"<td><input type='text' id='rate'/></td>"+
"<td><input type='text' id='amt'/></td></tr>");
The above one everytime adds same id for multiple elements when added to the dom. you can try to do this way:
$("#add").click(function () {
var i = $("#table1 tbody>tr:last").index();
var newrow = $("<tr><td><input type='text'/></td>" +
"<td><input type='text' class='num' id='qty" + (i) + "'/></td>" +
"<td><input type='text' class='num' id='rate" + (i) + "'/></td>" +
"<td><input type='text' class='num' id='amt" + (i) + "'/></td>");
newrow.insertAfter('#table1 tbody>tr:last');
return false;
});

Categories

Resources