How to update a table in html/js? - javascript

i have a select-tag, where i can select a charging station. Under the select-tag is a table, where the specifications of the charging station are displayed.
My problem is now: How can i update the table after selecting another charging station in the select tab?
Here's a picture of the view:
And the code:
var id = Model.ChargingZones[i].ChargingStationChargingZones[j].ChargingStationId;
var stations = (IList < ChargingStation > ) ViewBag.Stations;
var station = stations.FirstOrDefault(s => s.Id == id);
SelectList list;
if (station != null) {
list = new SelectList(stations, "Id", "ModelName", Model.ChargingZones[i].ChargingStationChargingZones[j].ChargingStationId);
} else {
list = new SelectList(ViewBag.Stations, "Id", "ModelName");
}
<select asp-for="ChargingZones[i].ChargingStationChargingZones[j].ChargingStationId" class="selectpicker form-control" data-style="btn-dark" data-live-search="true"
asp-items="list" onchange="updateTable(#i,#j)" title="---Säule auswählen---">
</select>
<script>
function updateTable(i, j) {
document.getElementById("table-" + i + "-" + j).update();
}
</script>
<span asp-validation-for="ChargingZones[i].ChargingStationChargingZones[j].ChargingStation.ModelName" class="text-danger"></span>
<table id="table-#i-#j" class="table table-hover table-striped table-bordered" style="white-space: normal; text-align: center">
<tr>
<th>Stecker</th>
<th>Anzahl</th>
<th>Leistung</th>
<th>Gleichzeitig<br/>Gleichtstrom</th>
</tr>
#{
if (list.SelectedValue != null)
{
ChargingStation s = new ChargingStation();
foreach (var item in stations)
{
if (item.Id.ToString() == list.SelectedValue.ToString())
{
s = item;
}
}
foreach (ChargingPoint point in s.ChargingPoints)
{
<tr>
<td>#point.ConnectorType.GetDisplayName()</td>
<td>#s.ChargingPoints.Count</td>
<td>#point.ChargingPower kW</td>
<td>#s.ParallelChargingPoints</td>
</tr>
}
}
}
</table>

Related

Check All checkbox not working across the table pagination razer mvc

I have implemented a checkall checkbox for the table but the table has pagination and DOM only gets the elements currently showing on the page. my implementation is not working on other paginations. how can we achieve this task?
.cshtml code
<table id="instruments" class="table table-bordered table-striped table-condensed table-hover smart-form has-tickbox" style="width: 100%;">
<thead>
<tr>
<th>
<input id="chkAffectCheckboxGroup" type="checkbox" />
</th>
<th data-class="expand" style="white-space: nowrap">#Model.idResource</th>
<th data-hide="phone" style="white-space: nowrap">#Model.SResource</th>
<th data-hide="phone" style="white-space: nowrap">#Model.LocationResource</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Instruments.Count; i++)
{
var values = Model.Instruments[i].Value.Split('~');
var status = values.Length > 0 ? values[0] : "";
var location = values.Length > 1 ? values[1] : "";
<tr>
<td>
<label class="checkbox">
#Html.CheckBoxFor(m => m.Instruments[i].Selected, new { #class = "chkInst" })
<i></i>
</label>
</td>
<td><label>#Model.Instruments[i].Text</label></td>
<td><label>#status</label></td>
<td><label>#location</label></td>
</tr>
}
</tbody>
</table>
Jquery Code
$(document).ready(
console.log("jquery called"),
manageCheckboxGroup('chkAffectCheckboxGroup', 'chkInst')
);
JavaScript Code
function manageCheckboxGroup(masterCheckboxId, slaveCheckboxesClass) {
$("#" + masterCheckboxId).click(function () {
$("." + slaveCheckboxesClass).prop('checked', this.checked);
});
$("." + slaveCheckboxesClass).click(function () {
if (!this.checked) {
$("#" + masterCheckboxId).prop('checked', false);
}
else if ($("." + slaveCheckboxesClass).length == $("." + slaveCheckboxesClass + ":checked").length) {
$("#" + masterCheckboxId).prop('checked', true);
}
});
}

Angular-6 based on the select inputbox and select dropdown not showing properly

This question is maybe asked, but that is not solving my issue.
The drop-down of key contains database, desktop and account. Based on the drop-down of key the value drop-down and inputbox will be changed.
https://stackblitz.com/edit/angular-ivy-zahevb?file=src%2Fapp%2Fapp.component.html
My issue: When I click 1st row it seems good.
But when I move on to 2nd row the data append not properly. And when I select account previuos row drop-down also changed as inputbox
Eg:
In 1st row I select Database,value should append ['mysql', 'oracle', 'mongo'] in drop-down
In 2nd row I select Desktop, value should append ['dell', 'lenovo', 'hp']
In 3rd row I select Account the inputbox will show
app.component.ts
import { Component, VERSION } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
dynamicArray: Array<any> = [];
newDynamic: any = {};
dbValue = ["mysql", "oracle", "mongo"];
desktopValue = [{'id':'1', 'name':'dell'}, {'id':'2', 'name':'lenovo'}, {'id':'3', 'name':'hp'}];
isdbShow:boolean = false;
isdesktopShow:boolean = false;
isaccountShow:boolean = false;
ngOnInit(): void {
this.newDynamic = { title1: "", title2: "", dropdownDataDb: [], dropdownDataDesktop: [] };
this.dynamicArray.push(this.newDynamic);
}
addRow(index) {
this.newDynamic = { title1: "", title2: "", dropdownDataDb: [], dropdownDataDesktop: [] };
this.dynamicArray.push(this.newDynamic);
console.log(this.dynamicArray);
return true;
}
deleteRow(index) {
if (this.dynamicArray.length == 1) {
return false;
} else {
this.dynamicArray.splice(index, 1);
return true;
}
}
changed(value, index) {
let dropdownDataDb;
let dropdownDataDesktop;
if (value == 1) {
this.isdbShow = true;
this.isdesktopShow = false;
this.isaccountShow = false;
this.dynamicArray[index].dropdownDataDb = this.dbValue;
}
if (value == 2) {
this.isdbShow = false;
this.isdesktopShow = true;
this.isaccountShow = false;
this.dynamicArray[index].dropdownDataDesktop = this.desktopValue;
}
if (value == 3) {
this.isdbShow = false;
this.isdesktopShow = false;
this.isaccountShow = true;
}
}
}
app.componet.html
<div class="container" style="margin-top: 5%">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Action</th>
<th>key</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let dynamic of dynamicArray; let i = index;">
<td (click)="deleteRow(i)">
<i class="fa fa-trash fa-2x"></i>
</td>
<td>
<select [(ngModel)]="dynamicArray[i].title1" class="form-control" #sel (change)="changed(sel.value, i)">
<option [value]='1'>Database</option>
<option [value]='2'>Desktop</option>
<option [value]='3'>Account</option>
</select>
</td>
<td>
<!-- show db data -->
<select *ngIf="isdbShow" [(ngModel)]="dynamicArray[i].title2" class="form-control">
<option *ngFor="let data of dynamicArray[i].dropdownDataDb;">{{data}}</option>
</select>
<!-- show desktop data -->
<select *ngIf="isdesktopShow" [(ngModel)]="dynamicArray[i].title2" class="form-control">
<option *ngFor="let data of dynamicArray[i].dropdownDataDesktop;">{{data?.name ? data?.name : data}}</option>
</select>
<!-- show account data -->
<input *ngIf="isaccountShow" type="text" [(ngModel)]="dynamicArray[i].title2" class="form-control">
</td>
</tr>
<tr>
<td (click)="addRow(0)">
<i class="fa fa-plus fa-2x"></i>
</td>
</tr>
</tbody>
</table>
</div>
ts code
dynamicArray: Array<any> = [];
newDynamic: any = {};
dbValue = ["mysql", "oracle", "mongo"];
desktopValue = [
{ id: "1", name: "dell" },
{ id: "2", name: "lenovo" },
{ id: "3", name: "hp" }
];
ngOnInit(): void {
this.newDynamic = {
title1: "",
title2: "",
dropdownDataDb: [],
dropdownDataDesktop: [],
isDropDown: true
};
this.dynamicArray.push(this.newDynamic);
}
addRow(index) {
this.newDynamic = {
title1: "",
title2: "",
dropdownDataDb: [],
dropdownDataDesktop: [],
isDropDown: true,
isText: false
};
this.dynamicArray.push(this.newDynamic);
console.log(this.dynamicArray);
return true;
}
deleteRow(index) {
if (this.dynamicArray.length == 1) {
return false;
} else {
this.dynamicArray.splice(index, 1);
return true;
}
}
changed(value: any, index: any) {
console.log(this.dynamicArray[index].title1);
if (value == 1) {
this.dynamicArray[index].isDropDown = true;
this.dynamicArray[index].isText = false;
this.dynamicArray[index].dropdownDataDb = this.dbValue;
}
if (value == 2) {
this.dynamicArray[index].isDropDown = true;
this.dynamicArray[index].isText = false;
this.dynamicArray[index].dropdownDataDesktop = this.desktopValue;
}
if (value == 3) {
this.dynamicArray[index].isDropDown = false;
this.dynamicArray[index].isText = true;
}
}
<div class="container" style="margin-top: 5%">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Action</th>
<th>key</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let dynamic of dynamicArray; let i = index;">
<td (click)="deleteRow(i)">
<i class="fa fa-trash fa-2x"></i>
</td>
<td>
<select [(ngModel)]="dynamicArray[i].title1" class="form-control" #sel (change)="changed(sel.value, i)">
<option [value]='1'>Database</option>
<option [value]='2'>Desktop</option>
<option [value]='3'>Account</option>
</select>
</td>
<td>
<!-- show db data -->
<select *ngIf="dynamicArray[i].title1 == 1 && dynamic?.isDropDown" [(ngModel)]="dynamicArray[i].title2" class="form-control">
<option *ngFor="let data of dynamicArray[i].dropdownDataDb;">{{data}}</option>
</select>
<!-- show desktop data -->
<select *ngIf="dynamicArray[i].title1 == 2 && dynamic?.isDropDown" [(ngModel)]="dynamicArray[i].title2" class="form-control">
<option *ngFor="let data of dynamicArray[i].dropdownDataDesktop;">{{data?.name ? data?.name : data}}</option>
</select>
<!-- show account data -->
<input *ngIf="dynamicArray[i].title1 == 3 && dynamic?.isText" type="text" [(ngModel)]="dynamicArray[i].title2" class="form-control">
</td>
</tr>
<tr>
<td (click)="addRow(0)">
<i class="fa fa-plus fa-2x"></i>
</td>
</tr>
</tbody>
</table>
</div>

Hide selected option at dynamically form jquery

I need to achieve something like when a user selects an option from one select box the option should be hidden for the other select boxes. When a selected option changes the previously selected option should become available again to the other select boxes. But my code seem like only can work at the static selection box.
var i = 0;
$('.addRow').on('click', function() {
addRow();
$('.s').change(function() {
let value = $(this).val();
$(this).siblings('.s').children('option').attr('disabled', false);
$('.s').each(function() {
$(this).siblings('.s').children('option[value=' + $(this).val() + ']').attr('disabled', 'disabled');
})
});
});
function addRow() {
var tr = '<tr class="cb" id="row_' + i + '"><td>';
tr += '<select class="s form-control select2" id="name1_' + i + ' first" name="name[]" >';
tr += '<option id="1">tan</option><option id="2">lim</option><option id="3">vin</option><option id="4">alex</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_' + i + '" class="form-control"></td>';
tr += '<td style="text-align:center">-';
tr += '</td></tr>';
i++;
$('tbody').append(tr);
}
$('tbody').on('click', '.remove', function() {
$(this).parent().parent().remove();
});
$('.savebtn').on('click', function() {
$('.listable .cb').each(function(index, item) {
console.log($('#amt1_' + index).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered listable">
<thead>
<tr class="text-center">
<th>name</th>
<th>amount</th>
<th style="text-align:center"><a href="#" class="btn btn-info addRow">+</th>
</tr>
</thead>
<tbody class="text-center"></tbody>
</table>
<button type="button" class="btn btn-primary savebtn">Save</button>
If you want to dynamically update each select, you will need to do a few things:
Have a dynamic list in a data structure
Be able to figure out what is selected
Update (or recreate) the dropdowns when:
a selection is made or
a row is added or
a row is removed
This way you separate the view from the data backing it.
Update: Instead of re-rendering the options for each select, I toggle their "disabled" state.
let rowId = 0;
const options = [
{ id: 1, name: "tan" },
{ id: 2, name: "lim" },
{ id: 3, name: "vin" },
{ id: 4, name: "alex" },
];
function getSelections() {
return $('select.select2')
.map((i, sel) => $(sel).val()).toArray()
.map(id => parseInt(id, 10));
}
function fixSelections() {
const selections = getSelections();
$('select.select2').each((i, sel) => {
let $sel = $(sel), val = $sel.val();
$sel.find('option').each((j, opt) => {
let $opt = $(opt);
if ($opt.val() !== val && selections.includes(parseInt($opt.val(), 10))) {
$opt.attr('disabled', true);
} else {
$opt.removeAttr('disabled');
}
});
});
}
function populateOptions() {
const selections = getSelections();
return options.map(option => {
return `
<option value="${option.id}"
${selections.includes(option.id) ? 'disabled="disabled"' : ''}>
${option.name}
</option>
`;
});
}
function addRow() {
const tr = `
<tr class="cb" id="row_${rowId}">
<td>
<select class="s form-control select2" id="name1_${rowId}_first" name="name[]">
${populateOptions()}
</select>
</td>
<td>
<input type="number" name="winlose[]" id="amt1_${rowId}" class="form-control">
</td>
<td style="text-align:center">
-
</td>
</tr>
`;
rowId++;
$('tbody').append(tr);
}
$('.addRow').on('click', function() {
addRow();
$('.s').change(function() {
let value = $(this).val();
$(this).siblings('.s')
.children('option')
.attr('disabled', false);
$('.s').each(function() {
$(this).siblings('.s')
.children('option[value=' + $(this).val() + ']')
.attr('disabled', 'disabled');
})
});
fixSelections();
});
$('tbody').on('click', '.remove', function() {
$(this).parent().parent().remove();
fixSelections();
});
$('.savebtn').on('click', function() {
$('.listable .cb').each(function(index, item) {
console.log($('#amt1_' + index).val());
});
});
$(document).on('change', 'select.select2', e => fixSelections());
option {
color: #000;
font-style: normal;
font-weight: bold;
}
option[disabled] {
color: #777;
font-style: italic;
font-weight: normal;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<table class="table table-bordered listable">
<thead>
<tr class="text-center">
<th>Name</th>
<th>Amount</th>
<th style="text-align:center"><a href="#" class="btn btn-info addRow">+</th>
</tr>
</thead>
<tbody class="text-center"></tbody>
</table>
<button type="button" class="btn btn-primary savebtn">Save</button>
</div>
My solution was to show and enable all everytime something changes then disable and hide all of the options with same value as the ones selected and re-enable and show the one selected in the current select:
$('.addRow').on('click', function() {
addRow();
$('.s').change(function() { //1
$('.s option').prop('disabled',false);//enable all options //n
$('.s option').show();//show all options //n
$('.s option:selected').each(function(index){// disable and hide all of the current selected values from other select boxes //1 to select boxes n
let value = $(this).val();
$('.s option[value='+value+']').prop('disabled',true);//disable all with same value //select boxes n
$('.s option[value='+value+']').hide();//hide them //select boxes n
$(this).prop('disabled',false);//re-enable the current one //1
$(this).show();//and show it //1
$(this).prop('selected',true);//just to be sure re-select the option afterwards //1
});
});
});
I think you can perform this thing with css check snippet
option:checked { display: none; }
option:checked { display: none; }
<select>
<option>A for Alex</option>
<option selected>B for Billy</option>
<option>C for Cody</option>
<option>D for Danny</option>
</select>

Value of other column in the row in dynamic row is not changing

I have a dynamic row here and I have created a drop down of product and I want that price is changed automatically when the drop down is selected.
<div>
#using (Html.BeginForm("SaveProduct", "Master", FormMethod.Post, new { #id = "frmProductDetail", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
// #Html.Hidden("ProductOrderId", Model.ProductOrderId)
// #Html.Hidden("ProductId", Model.ProductId)
<div class="row-fluid border-light-color">
<div class="padding-5">
<div class="span12">
<div class="clear"></div>
<div class="Col1">
<span>#Html.LabelFor("Customer Name"):</span>
</div>
<div class="Col2">
#Html.TextAreaFor(m => m.CustomerName, new { #name = "CustomerName", #id = "CustomerName", #class = "txtCustDetails" })
</div>
<div class="Col3">
<span>#Html.LabelFor("Contact Number"):</span>
</div>
<div class="Col4">
#Html.TextAreaFor(m => m.CustomerNumber, new { #name = "CustomerName", #id = "CustomerName", #class = "txtCustDetails" })
</div>
<div class="clear"></div>
<div class="Col1">
<span>#Html.LabelFor("FirstName"):</span>
</div>
<div class="row-fluid">
Add
</div>
<div class="row-fluid">
<table class="table table-bordered table-hover gridtable" id="tblProduct" showsequence="true">
<thead>
<tr>
<th style="width:20%">SR No.</th>
<th style="width:20%">Product Name</th>
<th style="width:20%">Rate</th>
<th style="width:20%">Quantity</th>
<th style="width:20%">Grand Total</th>
<th style="width:20%">Delete</th>
</tr>
</thead>
<tbody>
<tr id="0" style="display:none">
<td class="text-center"></td>
<td>
#Html.DropDownList("ProductId", Model.ProductName.ToSelectList(Model.ProductNameId.ToString(), "Name","Value"))
</td>
<td>
#Html.TextBoxFor(m=>m.priceDetail, new { #name = "ProductPrice1", #id = "ProductPrice1", #class = "txtCustDetails"})
</td>
<td>
#Html.TextBoxFor(m=>m.OrderQuantity, new { #name = "OrderQuantity", #id = "OrderQuantity", #class = "txtCustDetails"})
</td>
<td>
#Html.TextBoxFor(m=>m.GrandTotal, new { #name = "GrandTotal", #id = "GrandTotal", #class = "txtCustDetails"})
</td>
<td class="text-center vertical-middle">
<i class="icon-trash" ></i>
</td>
</tr>
<tr id="1">
<td class="text-center">1</td>
<td>
#Html.DropDownList("ProductId", Model.ProductName.ToSelectList(Model.ProductNameId.ToString(), "Name", "Value"))
</td>
<td>
#Html.TextBoxFor(m=>m.priceDetail, new { #name = "ProductPrice2", #id = "ProductPrice2", #class = "txtCustDetails"})
</td>
<td>
#Html.TextBoxFor(m=>m.OrderQuantity, new { #name = "OrderQuantity", #id = "OrderQuantity", #class = "txtCustDetails"})
</td>
<td>
#Html.TextBoxFor(m=>m.GrandTotal, new { #name = "GrandTotal", #id = "GrandTotal", #class = "txtCustDetails"})
</td>
<td class="text-center vertical-middle">
<i class="icon-trash" ></i>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
}
</div>
I am trying to do it through Jquery but I am having problem that the price changes automatically only in the first row and not in the other rows. Please help me so that it changes in every row individually.
var GetPriceUrl = BASEPATHURL + "/Master/GetPriceDetail";
jQuery(document).ready(function () {
jQuery('#btnAdd').on('click', function () { AddRow('#tblProduct') });
//jQuery('#btnSave').on('click', function () { SaveEmployees() });
jQuery('#tblProduct').on('click', "a[name='RemoveRow']", function () { RemoveRow(this) });
jQuery("#tblProduct tbody").sortable({
//handle: '.glyphicon-move',
update: function () {
Reorder('#tblProduct');
}
});
jQuery("select[name]*=ProductId").change(function () {
GetPriceByProductId(jQuery(this).val());
jQuery(this).css('border-color', '');
});
});
function AddRow(tableId) {
var row = jQuery(tableId + ' > tbody > tr:first').clone(true);
var index = parseInt(jQuery(tableId + ' > tbody > tr:visible').length);
jQuery("input, textarea, select", row).each(function () {
jQuery(this).attr("id", jQuery(this).attr("id") + "_" + (index + 1));
jQuery(this).val('');
});
jQuery(tableId).append(row);
jQuery(row).show().attr("id", index);
Reorder(tableId);
}
function RemoveRow(control) {
var tableId = "#" + jQuery(control).closest("table").attr("id");
jQuery(control).closest("tr").remove();
jQuery(tableId + ' > tbody > tr:visible').each(function (i, e) { jQuery(e).attr("id", i + 1) });
Reorder(tableId);
}
function Reorder(tableId) {
jQuery(tableId + '[showSequence = "true"] > tbody > tr:visible').each(function (i, e) {
jQuery(this).find("td:first").text(i + 1);
});
}
function GetPriceByProductId(ProductId) {
if (jQuery.trim(ProductId) != ""){
var postData = { ProductId: ProductId };
AjaxCall({
url: GetPriceUrl,
postData: postData,
httpmethod: 'POST',
calldatatype: 'JSON',
sucesscallbackfunction: 'OnSucessGetProductById'
});
}
}
function OnSucessGetProductById(response) {
jQuery("#ProductPrice2").val('');
jQuery("#ProductPrice2").val(response.priceDetail[0].ProductPrice);
}
Well I found the solution to this. Posting so that it may help others (sick of no response :( ). I saw that my AddRow function was incrementing the ProductId by 1. so firstly I took the Id of it and acquired its substring, then I concatenated it with the pricedetail so that it changes with every row. i have provided the function below.
jQuery("select[name]*=ProductId").change(function () {
var xyz = jQuery(this).attr("id");
Pro_Id = xyz.substring(xyz.lastIndexOf('_'));
GetPriceByProductId(jQuery(this).val());
jQuery(this).css('border-color', '');
jQuery('#btnSave').on('click', function () { InsertProductDetail(); });
jQuery('#btnUpdate').on('click', function () { InsertProductDetail(); });
});
function OnSucessGetProductById(response) {
//Jquery("input[name^='PriceDetail']").split('_').val("");
if (Pro_Id == "ProductId") {
jQuery("#ProductPrice").val('');
jQuery("#ProductPrice").val(response.priceDetail[0].ProductPrice);
}
else {
jQuery("#ProductPrice" + Pro_Id).val('');
jQuery("#ProductPrice" + Pro_Id).val(response.priceDetail[0].ProductPrice);
}
Pro_Id = "";
}
I hope this helps anyone in future. Thanks.

Duplicating table rows with clone

I am having an issue I am struggling to resolve. I have two tables
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin alignment" id="table1">
<thead>
<tr>
<th>Campaign Type</th>
<th>Deployment Date</th>
<th>Additional Information</th>
</tr>
</thead>
<tbody>
<tr class='template'>
<td>
<select class="selectType" name='typeInput[0][campType]' id="campInput">
<option value=""></option>
<option value="Main">Main</option>
<option value="Other">Standalone</option>
</select>
</td>
<td>
<input type="text" name='typeInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>
</td>
<td>
<textarea name='typeInput[0][addInfo]' id="additionalInput" placeholder='Additional Information' class="form-control noresize"></textarea>
</td>
</tr>
</tbody>
</table>
<a id='add' class="pull-right btn btn-default">Add Row</a>
<a id='delete' class="pull-right btn btn-default">Delete Row</a>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin alignment" id="table4">
<thead>
<tr>
<th>Additional Information</th>
<th>Deployment Date</th>
</tr>
</thead>
<tbody>
<tr class='template4'>
<td>
<textarea name='amendsInput[0][addInfo]' id="additionalInput" placeholder='Additional Information' class="form-control noresize"></textarea>
</td>
<td>
<input type="text" name='amendsInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>
</td>
</tr>
</tbody>
</table>
<a id='add4' class="pull-right btn btn-default">Add Row</a>
<a id='delete4' class="pull-right btn btn-default">Delete Row</a>
</div>
</div>
</div>
</div>
One table has 3 inputs, the other has 2. When the add button is pushed on either table, I am cloning the table row, which includes cloning a datepicker.
Things have been going fine but now I have a problem. The second table I end everything with 4 e.g. table4, template4, add4 and delete4. I then duplicated the Javascript from the preious table but added 4 to everything (I duplicated it because this table has different inputs). This resulted in the following code.
$(function() {
initJQueryPlugins();
$('#add').on('click', function() {
$last_row = $('#table1 > tbody > tr').last();
if(!hasValues($last_row)){
alert('You need to insert at least one value in last row before adding');
} else {
add_row($('#table1'));
}
});
$('#delete').on('click', function() { delete_row($('#table1')); });
$('#add4').on('click', function() {
$last_row = $('#table4 > tbody > tr').last();
if(!hasValues4($last_row)){
alert('You need to insert at least one value in last row before adding');
} else {
add_row4($('#table4'));
}
});
$('#delete4').on('click', function() { delete_row4($('#table4')); });
});
function add_row($table) {
var tr_id = $table.find('tr').length - 1;
var $template = $table.find('tr.template');
var $tr = $template.clone().removeClass('template').prop('id', tr_id);
$tr.find(':input').each(function() {
if($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker').removeData('datepicker');
}
var input_id = $(this).prop('id');
input_id = input_id + tr_id;
$(this).prop('id', input_id);
var new_name = $(this).prop('name');
new_name = new_name.replace('[0]', '['+ tr_id +']');
$(this).prop('name', new_name);
$(this).prop('value', '');
});
$table.find('tbody').append($tr);
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
$(".selectType", $tr).select2({
tags: true
});
}
function hasValues($row){
$optVal = $row.find('td option:selected').text();
$inputVal = $row.find('td input').val();
$textVal = $row.find('td textarea').val();
if($optVal != "" || $inputVal != "" || $textVal != ""){
return true;
} else {
return false;
}
}
function delete_row($table) {
var curRowIdx = $table.find('tr').length - 1;
if (curRowIdx > 2) {
$("#" + (curRowIdx - 1)).remove();
curRowIdx--;
}
}
function add_row4($table4) {
var tr_id = $table4.find('tr').length - 1;
var $template = $table4.find('tr.template4');
var $tr = $template.clone().removeClass('template4').prop('id', tr_id);
$tr.find(':input').each(function() {
if($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker').removeData('datepicker');
}
var input_id = $(this).prop('id');
input_id = input_id + tr_id;
$(this).prop('id', input_id);
var new_name = $(this).prop('name');
new_name = new_name.replace('[0]', '['+ tr_id +']');
$(this).prop('name', new_name);
$(this).prop('value', '');
});
$table4.find('tbody').append($tr);
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
}
function hasValues4($row4){
$inputVal = $row4.find('td input').val();
$textVal = $row4.find('td textarea').val();
if($inputVal != "" || $textVal != ""){
return true;
} else {
return false;
}
}
function delete_row4($table4) {
var curRowIdx = $table4.find('tr').length - 1;
if (curRowIdx > 2) {
$("#" + (curRowIdx - 1)).remove();
curRowIdx--;
}
}
function initJQueryPlugins() {
add_row($('#table1'));
add_row4($('#table4'));
}
I have set up a working FIDDLE
The problem is this. If you start adding a few rows in the first table, this all works fine. After this, add a few rows in the second table. This seems to work fine. However, now start deleting rows in the second table. For some reason it seems to also delete rows in the first table.
So my main question is why does this happen? Additionally, is there any way I can do this without duplicating the code? The second table does not use select2.
Thanks
You are deleting this:
$("#" + (curRowIdx - 1)).remove();
This id is also available in the first table, you have to choose a more specified selector
like:
$table4.find("#" + (curRowIdx - 1)).remove();
or better: (comment from K. Bastian above)
$table4.find('tr').last().remove()
I edited your sample here:
https://jsfiddle.net/cLssk6bv/
Here I also deleted the dublicated code, only the different insert method still exist:
https://jsfiddle.net/cLssk6bv/1/

Categories