Enter key to create new row and focus current input field - javascript

<table width="500" border="1">
<tr>
<td>No.</td>
<td>Name</td>
<td>Age</td>
<td>Phone</td>
</tr>
<tr>
<td>1</td>
<td><input type="text" class="inputs" name="name_1" id="name_1" /></td>
<td><input type="text" class="inputs" name="age_1" id="age_1" /></td>
<td><input type="text" name="phone_1" class="inputs lst" id="phone_1" /></td>
</tr>
</table>
<script>
var i = $('table tr').length;
$('.lst').on('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
html = '<tr>';
html += '<td>' + i + '</td>';
html += '<td><input type="text" class="inputs" name="name_' + i + '" id="name_' + i + '" /></td>';
html += '<td><input type="text" class="inputs" name="age_' + i + '" id="age_' + i + '" /></td>';
html += '<td><input type="text" class="inputs lst" name="phone_' + i + '" id="phone_' + i + '" /></td>';
html += '</tr>';
$('table').append(html);
$(this).focus().select();
i++;
}
});
$('.inputs').keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
}
});
</script>
In this form initially focus on first text box ,then press enter key it automatically focus to nearby input fields at dead end while we press enter Key then it create new row and focus to initial input field presented in newly created row
after that while we press enter key it doesn't focus to near by text field please help to resolve this issue.
In first row it work correctly while we entering second row it not working
please help

You need event delegation for dynamically generated elements like following.
var i = $('table tr').length;
$(document).on('keyup', '.lst', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
html = '<tr>';
html += '<td>' + i + '</td>';
html += '<td><input type="text" class="inputs" name="name_' + i + '" id="name_' + i + '" /></td>';
html += '<td><input type="text" class="inputs" name="age_' + i + '" id="age_' + i + '" /></td>';
html += '<td><input type="text" class="inputs lst" name="phone_' + i + '" id="phone_' + i + '" /></td>';
html += '</tr>';
$('table').append(html);
$(this).focus().select();
i++;
}
});
$(document).on('keydown', '.inputs', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="500" border="1">
<tr>
<td>No.</td>
<td>Name</td>
<td>Age</td>
<td>Phone</td>
</tr>
<tr>
<td>1</td>
<td><input type="text" class="inputs" name="name_1" id="name_1" /></td>
<td><input type="text" class="inputs" name="age_1" id="age_1" /></td>
<td><input type="text" name="phone_1" class="inputs lst" id="phone_1" /></td>
</tr>
</table>

Related

Autonumbering is not working on added rows

I have 2 functions. Add dynamic rows and Autonumbering. My problem is, my autonumbering is not working on my dynamically added rows. I wonder what could be the problem? The "class="form-control" is all the same for my input type field. However, it is still not working. I have provided my js fiddle below.
https://prnt.sc/124vuju
https://jsfiddle.net/rain0221/59k4c0yg/3/ // in "lb" column, type any number and hit ctrl+enter in order to do autonumbering
//this is my function for autonumbering
const inputs = document.querySelectorAll(".form-control");
inputs[0].addEventListener("keyup", e => {
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
})
//this is my function for adding dynamic rows.
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" id="auto" value="" class="form-control" type="number" readonly /></td>"' +
'<td><input id="weight' + rowIndex + '" name="weight' + rowIndex + '" type="number" /></td>"' +
'<td><input id="wingBand' + rowIndex + '" name="wingBand' + rowIndex + '" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
$(document).on('click', '.removerow', function() {
$(this).parents('tr').remove();
regenerate_auto_num();
});
function regenerate_auto_num() {
let count = 1;
$(".auto_num").each(function(i, v) {
$(this).val(count);
count++;
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" placeholder="" required id="auto" />
</td>
<td class="labelcell">
<input name="weight" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
</div>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
You need to find the elements inside eventListener event. Since you are finding the element global onload so if will not hold the elements added dynamically. You can move the blow code inside addEventListener keyup event.
const inputs = document.querySelectorAll(".form-control");
To attach the keyup event, you can use document.querySelectorAll(".form-control")[0] instead of inputs[0].
document.querySelectorAll(".form-control")[0].addEventListener("keyup", e => {
const inputs = document.querySelectorAll(".form-control");
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
});
I can see that you have assigned the 'form-control' class only for LB# column so autonumber will be generate only for LB#. In case you want to generate autonumber for all the columns, assign the class="form-control" to each added dynamically.
The problem is that you are addding keyup listeners only to those elements that are already present in the DOM at the time you are adding them.
What you need instead is called delegate listeners, and it means that you rely on the mechanism that most events bubble up in the DOM, allowing you to attach the keyup listener to an element that is an ancestor to all the input elements of interest.
Inside that listener, you then check if the element they event came from is one you want to handle.
//this is my function for autonumbering
const inputAncestor = document.querySelector("tbody");
inputAncestor.addEventListener("keyup", e => {
if (
e.target.matches('input.form-control') &&
((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10))
) {
const inputs = document.querySelectorAll(".form-control");
let value = parseInt(e.target.value);
inputs.forEach((inp) => {
if (inp !== e.target) {
inp.value = ++value;
}
})
}
})
//this is my function for adding dynamic rows.
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form-control" type="number" readonly /></td>"' +
'<td><input id="weight' + rowIndex + '" name="weight' + rowIndex + '" type="number" /></td>"' +
'<td><input id="wingBand' + rowIndex + '" name="wingBand' + rowIndex + '" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
$(document).on('click', '.removerow', function() {
$(this).parents('tr').remove();
regenerate_auto_num();
});
function regenerate_auto_num() {
let count = 1;
$(".auto_num").each(function(i, v) {
$(this).val(count);
count++;
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" placeholder="" required id="auto" />
</td>
<td class="labelcell">
<input name="weight" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan=5><button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
Unfortunately, your code has several more problems, which I tried to fix.
As mentioned in the first comment to your question, you cannot have a div as a child of tbody. Only tr is allowed here.
You are using duplicate id value auto. That is invalid HTML.
In your markup, you have the class form-control on all the inputs. In your dynamically added markup it's only on the first input. Which version is the correct one?
In your tfoot you had the button as direct child. This is, again, invalid HTML. The only child element(s) tfoot can have is tr.
The very first row in your table describes the columns and acts as your table's header, yet it did not reside in the thead part of your table.

Get Ajax response to table's td input

I'm trying to retrieve Ajax response to <td> row input but it's not working as expected, it's binding to input but when trying to add another product to row it's replacing previous one.
Example 1:
In above example as you can see first I have added "Camera" to the row and then trying to add another product i.e "Mobile" but it's replacing first one.
Then I have tried another approach but it's not retrieving data in input field.
Example 2:
In above example it's successfully adding data to the next row but it's not editable.
HTML:
<div class="table-responsive">
<table class="table table-bordered table-condensed" id="mytable">
<div class="row">
<div>
<input type="text" id="search" class="form-control"> //To search product by id
</div>
<div>
<button type="button" name="add" id="add" class="btn btn-success">Add Row</button>
</div>
</div>
<thead>
<tr>
<th>Product</th>
<th>Qty</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tr>
<td><input type="text" name=" addmore[0][name]" id="pname" class="form-control"/></td> //This part commented in Example 2
<td><input type="text" name="addmore[0][qty]" id="qty" class="form-control"/></td> //This part commented in Example 2
<td><input type="text" name="addmore[0][price]" id="price" class="form-control"/></td> //This part commented in Example 2
</tr>
</table>
</div>
Script to retrieve data (Example 1):
<script>
$('#search').on('keydown', function(e) {
if(e.which == 13){
var proid = $("#search").val();
//alert(proid);
$.ajax({
url: '{{ URL::to('search-product/')}}'+"/"+ proid,
type: "Get",
dataType:"json",
success: function (response)
{
$.each(response, function (i, item) {
$('#pname').val(item.product_name);
$('#qty').val(1);
$('#price').val(item.product_price);
});
}
});
}
});
</script>
Script to retrieve data (Example 2):
<script>
$('#search').on('keydown', function(e) {
if(e.which == 13){
var proid = $("#search").val();
//alert(proid);
$.ajax({
url: '{{ URL::to('search-product/')}}'+"/"+ proid,
type: "Get",
dataType:"json",
success: function (response)
{
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.product_name +
'</td><td>' + '1' +
'</td><td>' + item.product_price +
'</td></tr>';
});
$('#mytable').append(trHTML);
}
});
}
});
</script>
Script to add and remove rows:
<script type="text/javascript">
var i = 0;
$("#add").click(function(){
++i;
$("#mytable").append('<tr><td><input type="text" name="addmore['+i+'][name]" class="form-control" /></td><td><input type="text" name="addmore['+i+'][qty]" class="form-control" /></td><td><input type="text" name="addmore['+i+'][price]" class="form-control" /></td><td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
});
$(document).on('click', '.remove-tr', function(){
$(this).parents('tr').remove();
});
</script>
In response to my comment, replace in the 2nd example:
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.product_name +
'</td><td>' + '1' +
'</td><td>' + item.product_price +
'</td></tr>';
});
$('#mytable').append(trHTML);
with:
$.each(response, function (i, item) {
trHTML += '<tr>' +
'<td><input type="text" name=" addmore[0][name]" id="pname' + item.product_name + '" class="form-control" value="' + item.product_name + '"/></td>' +
'<td><input type="text" name=" addmore[0][qty]" id="qty' + item.product_name + '" class="form-control" value="1"/></td>' +
'<td><input type="text" name=" addmore[0][price]" id="price' + item.product_name + '" class="form-control" value="' + item.product_price + '"/></td>' +
'</tr>';
});
$('#mytable').append(trHTML);

How to add checkboxes dynamically to the table in javascript

I have a problem in how to add checkboxes dynamically to the javascript code. I have different scenario. I am getting data through ajax So I need to add table thead in the javascript rather than the html. But now I want to add Checkboxes to my thead. Indeed I added them but I don't know how to check them all with one checkbox. I write also code for that to select all but thats only working when my thead is in the html. Below is my code and it will give you a clear view. Try to read it in the editor because its a more compicated :)
//Javascript
$(document).ready(function() {
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
$('select[name="class_id"]').on('change', function() {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/attendance/ajax/' + classID,
type: "GET",
dataType: "json",
success: function(data) {
var markup = '';
markup += '<tr><th style="width: 2%" class="align-middle text-center"><input type="checkbox" id="options"></th><th style="width: 2%" class="align-middle text-center">#</th> <th style="width: 15%" class="text-center">Student ID<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Student Name<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Attendance<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Date<input type="text" class="form-control" disabled></th> <th style="width: 15%;" class="align-middle text-center">Actions</th> <tr>';
$.each(data, function(key, value) {
markup += '<tr> <td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]"></td> <td><input type="hidden" value="' + value.id + '" name="id[]">' + value.id + '</td> <td><input type="hidden" value="' + value.student_id + '" name="student_id[]">' + value.student_id + '</td> <td><input type="hidden" value="' + value.first_name + '" name="first_name[]"><input type="hidden" value="' + value.last_name + '" name="last_name[]">' + value.first_name + ' ' + value.last_name + '<td><input type="hidden" value="' + value.attendance + '" name="attendance[]">' + value.attendance + '</td>' + '<td><input type="hidden" value="' + value.created_at + '" name="created_at[]">' + value.created_at + '</td>' + '<td style=" width=12%" class="text-center"> <a><button title="Edit" class="btn btn-outline-primary"><span class="fas fa-pencil-alt"></span></button></a> </td>' + '</td> <tr>';
});
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
//For selecting all checkboxes
$(document).ready(function() {
$('#options').click(function() {
if (this.checked) {
$('.checkBoxes').each(function() {
this.checked = true;
});
} else {
$('.checkBoxes').each(function() {
this.checked = false;
});
}
});
});
The issue is the execution of event handlers on DOM elements.
The browser renders and executes code from top to bottom (in most cases).
This means that you execute $('#options').click() before you add all checkboxes via Ajax request.
Therefore you are trying to attach an event handler to elements which are not present at that moment of time.
To make it work, you have to add an event listener to the parent element
$('table[id="studentsData"]').on('click', '#options', function() {})
Source:
http://api.jquery.com/on/
The second argument is a selector you are going to target

reading dynamically added input values into an array php

Every thing is working expect that on adding the dynamic fields,the input added is not captured into the array.Only the values in the only created input are read. HTML PART
<table class="table table-bordered table-hover order-list" >
<thead>
<tr><td>Product</td><td>Price (Ksh.) </td><td>Qty</td><td> (Ksh.)</td></tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control" name="product[]" required="" /></td>
<td><input type="text" class="form-control" name="price[]" required/></td>
<td><input type="text" class="form-control" name="quantity[]" /></td>
<td><input type="text" name="linetotal[]" readonly="readonly" /></td>
<td><a class="deleteRow"> x </a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: center;">
<input type="button" id="addrow" value="Add Product" />
</td>
</tr>
<tr>
<td colspan="5">
Grand Total: Ksh.<input type="text" name="grandtotal" readonly="readonly" /><span id="grandtotal"></span>
</td>
</tr>
</tfoot>
</table>
THE javascript to sum up the get the sub total and grand total is as below:
$(document).ready(function () {
var counter = 1;
$("#addrow").on("click", function () {
counter++;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" name="product' + counter + '"/></td>';
cols += '<td><input type="text" name="price' + counter + '"/></td>';
cols += '<td><input type="text" name="quantity' + counter + '"/></td>';
cols += '<td><input type="text" name="linetotal' + counter + '" readonly="readonly"/></td>';
cols += '<td><a class="deleteRow"> x </a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
});
$("table.order-list").on("change", 'input[name^="price"], input[name^="quantity"]', function (event) {
calculateRow($(this).closest("tr"));
calculateGrandTotal();
});
$("table.order-list").on("click", "a.deleteRow", function (event) {
$(this).closest("tr").remove();
calculateGrandTotal();
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
var qty = +row.find('input[name^="quantity"]').val();
var linetotal = +row.find('input[name^="linetotal"]').val((price * qty).toFixed(2));
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="linetotal"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
the php part to read the array is
if(isset($_POST['cinvoice']) && $_SERVER["REQUEST_METHOD"] == "POST" &&is_array($_POST["product"]) && is_array($_POST["quantity"]) && is_array($_POST["price"]) && is_array($_POST["linetotal"]))
{
$recordid="";
$firstname="";
$product="";
$quantity="";
$price="";
$linetotal="";
foreach ($_POST["product"] as $key => $prod) {
$product .= $prod.",";
}
foreach ($_POST["quantity"] as $key => $qty){
$quantity.=$qty. ",";
}
foreach ($_POST["price"] as $key => $prc) {
$price.=$prc. ",";
}
foreach ($_POST["linetotal"] as $key => $linetotal) {
$linetotal.=$linetotal. ",";
}
you should pass textbox name as an array:
cols += '<td><input type="text" name="product[]"/></td>';
cols += '<td><input type="text" name="price[]"/></td>';
cols += '<td><input type="text" name="quantity[]"/></td>';
cols += '<td><input type="text" name="linetotal[]" readonly="readonly"/>
Also you can use implode function in php
foreach ($_POST["product"] as $key => $prod) {
$product .= $prod.",";
}
to
$product = implode(',', $_POST["product"])

jQuery UI datepicker function calling dynamically

This is function which is reposible for create row dynamically.
$(document).ready(function() {
var count = 1;
var row = $("table#myTable tr:eq(1)");
$(document).on('click', '#addrow', function() {
$('#myTable tbody').append('<tr class="prototype" id="' + count + '"> <td align="center" ><input type="text" size="10" name="grnno[' + count + ']" id="grnno" class="required" align="right"/></td><td align="center" ><input type="text" name="paymentdateid="datepicker size="10" class="datepicker" align="right" /></td><td align="center"><select id="bankname" name="bankname"><option value="">Select Bank Name</option><option value="SBI">SBI</option><option value="UBI">UBI</option><option value="UCO">UCO</option><option value="HDFC">HDFC</option></select></td><td align="center" ><input type="text" name="amount[' + count + ']" id="amount[' + count + ']" size="10" class="required" align="right"/></td><td align="center"><input type="button" value="Delete" onclick="deleteRow(this)"></td><td style="display:none;"><input type="text" name="id[]" value="' + count + '" class="id" /></td></tr>');
count++;
});
});
now I want to attach this function with the field "Payment Date" as I need the datepicker dynamically
.
$(function() {
$( "#datepicker" ).datepicker({
inline: true
});
});
I have to mentioned here customizing the append function is not possible .
Since it is a widget, you need to initialize it once the element is added to the dom.
So
Use appendTo() to get back the tr that is added
use class for the datepicker instead of id since ID of an element must be unique
after appending the tr find the datepicker element and initialize the widget
Try
$(document).ready(function () {
var count = 1;
var row = $("table#myTable tr:eq(1)");
$(document).on('click', '#addrow', function () {
var $tr = $('<tr class="prototype" id="' + count + '"> <td align="center" ><input type="text" size="10" name="grnno[' + count + ']" id="grnno" class="required" align="right"/></td><td align="center" ><input type="text" name="paymentdate classs="datepicker size="10" class="datepicker" align="right" /></td><td align="center"><select id="bankname" name="bankname"><option value="">Select Bank Name</option><option value="SBI">SBI</option><option value="UBI">UBI</option><option value="UCO">UCO</option><option value="HDFC">HDFC</option></select></td><td align="center" ><input type="text" name="amount[' + count + ']" id="amount[' + count + ']" size="10" class="required" align="right"/></td><td align="center"><input type="button" value="Delete" onclick="deleteRow(this)"></td><td style="display:none;"><input type="text" name="id[]" value="' + count + '" class="id" /></td></tr>').appendTo('#myTable tbody');
$tr.find(".datepicker").datepicker({
inline: true
});
count++;
});
});

Categories