How to generate a new table row with an onClick event - javascript

I have a table with 2 columns and 1 row. I would like it to generate another row with a clean set of inputs when users click the "add new row" button it.
Current HTML table:
<table class="table table-bordered">
<thead>
<tr>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>
<td><input type="file" onchange="previewFile()"><img src="" height="80"></td><br>
</tr>
</tbody>
</table>
<input type="button" value="Add new row">
How it currently looks:
I want the table add another table row when the user clicks the "Add new row" button.

Very easy. You can use insertAdjacentHTML
function addNewRow() {
let tds = document.getElementsByTagName("td");
tds[tds.length - 2].insertAdjacentHTML('afterend', '<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>')
}
<table class="table table-bordered">
<thead>
<tr>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>
<td><input type="file" onchange="previewFile()"><img src="" height="80"></td><br>
</tr>
</tbody>
</table>
<input type="button" value="Add new row" onclick="addNewRow()">
With increasing placeholder:
let i = 1;
function addNewRow() {
i++;
let tds = document.getElementsByTagName("td");
tds[tds.length - 2].insertAdjacentHTML('afterend', `<td><textarea rows="5" cols="1" placeholder="Enter task description here #${i}"></textarea></td>`)
}
<table class="table table-bordered">
<thead>
<tr>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea rows="5" cols="1" placeholder="Enter task description here #1"></textarea></td>
<td><input type="file" onchange="previewFile()"><img src="" height="80"></td><br>
</tr>
</tbody>
</table>
<input type="button" value="Add new row" onclick="addNewRow()">
jQuery solution:
function addNewRow() {
$("td").eq($("td").length - 2).after('<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>');
}
<table class="table table-bordered">
<thead>
<tr>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>
<td><input type="file" onchange="previewFile()"><img src="" height="80"></td><br>
</tr>
</tbody>
</table>
<input type="button" value="Add new row" onclick="addNewRow()">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

Would highly recommend you read up on render functions and implement here:
https://gomakethings.com/rendering-content-with-vanilla-javascript/

Related

Select the first html table row on page load using JS or JQUERY

Can someone help to select the the first row of my html table on page load using jquery or javascript.
after the page loads, it should select/highlight the first row and put all of the data from the selected row to the input boxes.
Here is my HTML CODE
HTML
<table id="tblCases">
<thead>
<tr>
<th>CASE KEY</th>
<th>DEPARTMENT CASE</th>
<th>DEPARTMENT</th>
<th style="display: none;">DEPT CODE</th>
<th style="display: none;">CHARGE</th>
<th>OFFENSE CODE</th>
<th>LAB CASE</th>
<th>INCIDENT REPORT DATE</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<p>
<b>Case Details</b>
</p>
<table>
<tr>
<td>
Department Case
</td>
<td>
<input type="text" name="Department Case #" id="txtDepartmentCase" value="" />
</td>
</tr>
<tr>
<td>
Department
</td>
<td>
<select id="drpDepartment">
</select>
</td>
</tr>
<tr>
<td>
Charge
</td>
<td>
<select id="drpCharge">
</select>
</td>
</tr>
<tr>
<td>
Lab Case
</td>
<td>
<input type="text" name="Lab Case" id="txtLabCase" value="" />
</td>
</tr>
<tr>
<td>
Incident Report Date
</td>
<td>
<input type="text" name="Incident Report Date" id="txtIncidentReportDate" value="" />
</td>
</tr>
<tr>
<td>
<input type="hidden" name="Case key" id="txtCaseKey" value="" />
</td>
</tr>
</table>
<br />
<table>
<tr>
<td>
<input type="button" value="Edit" id="btnEdit" onclick="" />
</td>
<td>
<input type="button" value="Save" id="btnSave" onclick="SaveData(); this.form.reset();" />
</td>
<td>
<input type="button" value="Cancel" id="btnCancel" onclick="" />
</td>
</tr>
</table>
Here is my JS CODE, Here I include the onclick selection on the html table and also I include the function for populating the input boxes with the data from the selected row.
Javascript/jquery
$(function () {
///<summary> Highlights the row when selected</summary>
///<param name="editing" type="text">Editing state</param>
///<returns type="text"></returns>
$('#tblCases tr').click(function () {
if (isEditing) {
return;
}
$('#tblCases tr').removeClass('selectedRow');
$(this).addClass('selectedRow');
});
});
var table = document.getElementById("tblCases");
var rIndex;
for (var i = 1; i < table.rows.length; i++) {
///<summary>Display selected row data in text input.</summary>
///<param name="editing" type="text">Editing state</param>
/// <returns type="text"></returns>
table.rows[i].onclick = function () {
if (isEditing) {
return;
}
rIndex = this.rowIndex;
console.log(rIndex);
document.getElementById("txtCaseKey").value = this.cells[0].innerHTML;
document.getElementById("txtDepartmentCase").value = this.cells[1].innerHTML;
document.getElementById("drpDepartment").value = this.cells[3].innerHTML;
document.getElementById("drpCharge").value = this.cells[5].innerHTML;
document.getElementById("txtLabCase").value = this.cells[6].innerHTML;
document.getElementById("txtIncidentReportDate").value = this.cells[7].innerHTML;
};
}
function setEditingState(editing) {
///<summary>Defines the editing state which inlcude the behavior of buttons, input fields and row selection if a certain button was clicked</summary>
///<param name="editing" type="button; text">Editing state</param>
isEditing = editing;
// Disable or enable fields.
$('#txtDepartmentCase').attr('disabled', !editing);
$('#drpDepartment').attr('disabled', !editing);
$('#drpCharge').attr('disabled', !editing);
$('#txtLabCase').attr('disabled', !editing);
$('#txtIncidentReportDate').attr('disabled', !editing);
// Disable or enable buttons.
$('#btnEdit').attr('disabled', editing);
$('#btnSave').attr('disabled', !editing);
$('#btnCancel').attr('disabled', !editing);
}
Here's something to get you started:
var first_name = $('#source_table').find('tbody tr:first td:first').text();
var last_name = $('#source_table').find('tbody tr:first td:nth-child(2)').text();
var age = $('#source_table').find('tbody tr:first td:nth-child(3)').text();
$('#first_name').val(first_name);
$('#last_name').val(last_name);
$('#age').val(age);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="source_table" border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Joe</td>
<td>Hunt</td>
<td>20</td>
</tr>
<tr>
<td>Jane</td>
<td>Middletow</td>
<td>19</td>
</tr>
</tbody>
</table>
<br/>
<table>
<tr>
<td>First Name :</td>
<td><input type="text" id="first_name"></td>
</tr>
<tr>
<td>Last Name :</td>
<td><input type="text" id="last_name"></td>
</tr>
<tr>
<td>Age :</td>
<td><input type="text" id="age"></td>
</tr>

How to select last row of a table?

I have the following div:
<div data-object-id="dsOrders" class = "OrderList" >
<div class="table-responsive m-y-1">
<table class="table">
<thead>
<tr>
<th style="width:110px;">ID</th>
<th style="width:110px;"> Order Date</th>
</tr>
<!-- FILTER ROW -->
<tr>
<td>
<input data-search="OrderID" class="form-control form-control-sm">
</td>
<td>
<input data-search="OrderDate" class="form-control form-control-sm">
</td>
</tr>
</thead>
<tbody>
<tr data-repeat data-active>
<td data-field="OrderID" class = "OrderID"></td>
<td data-field="OrderDate"></td>
</tr>
</tbody>
</table>
</div>
</div>
How do I make it select the last row of it with javascript or jquery? I've tried doing it like this
$("[.OrderList][tr:last]").focus();
But with no success
Use this code:
.OrderList >.table > tbody > tr:last-child { background:#ff0000; }
Try this :
$('#yourtableid tr:last').attr('id');
or this:
$("#TableId").find("tr").last();
Hope this if helpful :)
console.log($(".OrderList tr").last().html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-object-id="dsOrders" class = "OrderList" >
<div class="table-responsive m-y-1">
<table class="table">
<thead>
<tr>
<th style="width:110px;">ID</th>
<th style="width:110px;"> Order Date</th>
</tr>
<!-- FILTER ROW -->
<tr>
<td>
<input data-search="OrderID" class="form-control form-control-sm">
</td>
<td>
<input data-search="OrderDate" class="form-control form-control-sm">
</td>
</tr>
</thead>
<tbody>
<tr data-repeat data-active>
<td data-field="OrderID" class = "OrderID"></td>
<td data-field="OrderDate"></td>
</tr>
</tbody>
</table>
</div>
</div>
Try this code You can achieve it by:
$('#first table:last tr:last')
$('#yourtableid tr:last').attr('id').focus();
or
$('#yourtableid tr:last')[0].focus();
should work.
console.log($(".OrderList table tr:last").html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-object-id="dsOrders" class = "OrderList" >
<div class="table-responsive m-y-1">
<table class="table">
<thead>
<tr>
<th style="width:110px;">ID</th>
<th style="width:110px;"> Order Date</th>
</tr>
<!-- FILTER ROW -->
<tr>
<td>
<input data-search="OrderID" class="form-control form-control-sm">
</td>
<td>
<input data-search="OrderDate" class="form-control form-control-sm">
</td>
</tr>
</thead>
<tbody>
<tr data-repeat data-active>
<td data-field="OrderID" class = "OrderID"></td>
<td data-field="OrderDate"></td>
</tr>
</tbody>
</table>
</div>
</div>

Window.location is not working on javascript

I need to redirect to another view using javascript on button click. The reason I need to use the javascript is because I need the "Account Id" of the row I am clicking. Below is the my code
This is to render the page
<link rel="stylesheet" type="text/css"
href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css">
<link href="#Url.Content("~/css/bootstrap.css")" rel="stylesheet">
<link href="~/Content/themes/base/all.css" rel="stylesheet" />
<script>
$(document).ready(function () {
$("#acctInfo").DataTable();
//$(".td_0").hide();
});
</script>
<!-- Page Title
============================================= -->
<section id="page-title">
<div class="container clearfix">
<h1>View Accounts</h1>
</div>
</section><!-- #page-title end -->
<section id="content">
<div class="content-wrap">
<div class="container clearfix">
<table class="table table-striped table-condensed table-hover" id="acctInfo">
<thead>
<tr>
<th class="td_0">Account Id</th>
<th>Employee Id</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Business Name</th>
<th>Account Type</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var i in Model.AccountsViews)
{
<tr id="rowx">
<td> #Html.DisplayFor(m => i.AcctId)</td>
<td> #Html.DisplayFor(m => i.EmployeeId)</td>
<td> #Html.DisplayFor(m => i.FirstName)</td>
<td> #Html.DisplayFor(m => i.MiddleName)</td>
<td> #Html.DisplayFor(m => i.LastName)</td>
<td> #Html.DisplayFor(m => i.BusinessName)</td>
<td> #Html.DisplayFor(m => i.AccountType)</td>
<td>Detail</td>
<td>Edit</td>
<td>Delete</td>
#*<td>
<input type="button" value="Edit" class="btn btn-success form-control" onclick="EditSelected(this)">
<input id="btn_edit[]" type="button" value="Edit" class="btn btn-success form-control" />
</td>
<td>
<input type="button" value="Delete" class="btn btn-danger btn-success form-control" />
</td>*#
</tr>
}
</tbody>
</table>
</div>
</div>
</section>
<div id="divEdit" style="display: none;">
<input type="hidden" id="hidId"/>
<table>
<tr>
<td>Employee Id</td>
<td><input type="text" id="txtEmployeeId" class="form-control"/></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" id="txtFirstName" class="form-control"/></td>
</tr>
<tr>
<td>Middle Name</td>
<td><input type="text" id="txtMiddleName" class="form-control"/></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" id="txtLastName" class="form-control"/></td>
</tr>
<tr>
<td>Business Name</td>
<td><input type="text" id="txtBusinessName" class="form-control"/></td>
</tr>
<tr>
<td>Account Type</td>
<td>
#Html.DropDownList("ddlAccount", new List<SelectListItem>
{
new SelectListItem{Text = "Supplier", Value = "Supplier"},
new SelectListItem{Text = "Employee", Value = "Employee"}
}, new{#class="form-control", id="ddlAccount"})
</td>
</tr>
</table>
</div>
This is the javascript to navigate me to another view
$('a.lnkDetail').on("click", function () {
var row = $(this).closest('tr');
var acctId = row.find("td:eq(0)").html().trim();
var url = '#Url.Action("ViewAccountDetail", "AccountWVehicle")?acctId=' + acctId;
Window.location = url;
return false;
});
When I use the alert(url), "I get the correct url like so "/ViewAccountDetail/AccountVehicle?acctId=7"
Your help is very much appreciated.
Try setting location.href to your new url, for example:
location.href = '/'
window.location.href = url; will work
Try this.
$('a.lnkDetail').on("click", function (event) {
event.preventDefault();
var row = $(this).closest('tr');
var acctId = row.find("td:eq(0)").html().trim();
window.location = '#Url.Action("ViewAccountDetail", "AccountWVehicle")?acctId=' + acctId;
});
More info here: What is the difference between Window and window?

Bootstrap 3 resize table data and input fields

I am trying to resize the input/td fields for a table, but cannot seem to get it working. Ive been referencing the stack post below. Still no luck.
stack-post-ref
jsfiddle-for-table
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>XS</th>
<th>S</th>
<th>M</th>
<th>L</th>
<th>XL</th>
<th>XXL</th>
<th>XXXL</th>
</tr>
</thead>
<tbody>
<tr>
<td class="col-md-1"><input type="number" name="xs" ng-model="order.size.extra_small"></td>
<td class="col-md-1"><input type="number" name="s" ng-model="order.size.small"></td>
<td class="col-md-1"><input type="number" name="m" ng-model="order.size.medium"></td>
<td class="col-md-1"><input type="number" name="l" ng-model="order.size.large"></td>
<td class="col-md-1"><input type="number" name="xl" ng-model="order.size.extra_large"></td>
<td class="col-md-1"><input type="number" name="xxl" ng-model="order.size.double_extra_large"></td>
<td class="col-md-1"><input type="number" name="xxxl" ng-model="order.size.triple_extra_large"></td>
</tr>
</tbody>
</table>
</div>
add form-control class to your input field https://jsfiddle.net/NourSammour/u2c09yb5/1/
For me this works:
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type... /></td>
<td>libero</td>
<td>Sed</td>
<td>cursus</td>
<td>ante</td>
</tr>
<tr>
<td>1,004</td>
<td>dapibus</td>
<td>diam</td>
<td>Sed</td>
<td>nisi</td>
</tr>
</tbody>
</table>
</div>

Angular JS ng-repeat for table row

I am using the following bootstrap table:
<table class="table table-striped">
<thead>
<tr>
<th>Episode Date</th>
<th>Day</th>
<th>Projected Cost</th>
<th>Comments</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="epi in episodes">
<td>
<input type="hidden" ng-model="epi.COST_PRG_EPS_TXN_ID" />
<label>{{epi.PRG_EPISODE_DATE_DIS | date:'dd-MMM-yyyy'}} </label>
</td>
<td>{{ epi.PRG_EPISODE_DAY }}</td>
<td>
<input type="text" ng-model="epi.COST_PROJECTED" onkeypress="return OnlyNumeric(event);" />
</td>
<td>
<input type="text" ng-model="epi.COMMENTS" />
</td>
</tr>
</tbody>
</table>
I am getting the error:
TypeError: Cannot read property 'insertBefore' of null
when I use ng-repeat for table row (tr).
However, when I cut and paste the ng-repeat to tbody, it works properly.
The requirement is to repeat tr and not tbody inside the table. How can I do it?
http://i.imgur.com/D52R9lq.png

Categories