Insert multiple rows to a table using Javascript - javascript

I'm trying to insert multiple rows to a table based on an input value, i used this code but it doesn't work:
function AddRows() {
var RowNumber = document.getElementById('quantite').value;
var table = document.getElementById('articleTable');
for (var i = 0; i < RowNumber; i++)
{
table.insertRow();
};
}
<div class="col-4">
<div class="form-group">
<label asp-for="Quantite" class="control-label"></label>
<input asp-for="Quantite" class="form-control" id="quantite" />
<span asp-validation-for="Quantite" class="text-danger"></span>
</div>
</div>
<button type="button" class="btn btn-primary" onclick="AddRows()">Add articles</button>
<table class="table table-bordered" id="articleTable" style="margin-top:10px;">
<thead>
<tr>
<th>Numero de Serie</th>
<th>Marque</th>
<th>Etat</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
So what's wrong in my code or is there any better way to add rows to html table based on an input value?

Related

jQuery validation on dynamic table form not working on using blur

I am creating form dynamically which has n rows (coming from array having n elements). Form fields have two type of columns (text & number) which I have given different id.
Although JQuery validation is working but "validate parts button" is not responding correctly. From the code condition it should not be enabled in case text is not valid.
Thanks..!
<div class="container-sm">
<div class="col-md-12 text-center">
<input class="btn btn-outline-primary" type="button" onclick = "buildTagPartsTable()" id="partNum" style="height:40px; width:220px" value="Enter Form Details#">
</div>
</div>
<div class="container-sm">
<div class="row">
<form id = "partsQuantForm">
<div class="col-lg-12" style="width:700px;overflow:auto; max-height:400px;">
<div class="partsTagsForm">
<table class="table table-striped" id="validTagsParts" style="width:100%;">
<thead>
<tr>
<th>Valid Row</th>
<th>Part </th>
<th># </th>
<th>Part </th>
<th># </th>
</tr>
</thead>
<tbody id="tagsPartsTable"></tbody>
</table>
</div>
<div class="col-md-12 text-center">
<input class="btn btn-outline-primary" type="button" id="tagsParts" style="height:40px; width:220px" value="Validate Parts ">
</div>
</div>
</form>
</div>
</div>
<script>
function buildTagPartsTable(){
validTagsInfo = ['Row1', 'Row2', 'Row3', 'Row4', 'Row5'];
var table = "<table>";
for (let key in validTagsInfo) {
table += `<tr>
<td>${validTagsInfo[key]}</td>
<td><input type="text" class="form-control" id = "partInfo" name="partInfo[0]" style="width:5em" minlength="5" maxlength="5" ></td>
<td><input type="number" class="form-control" id = "partQuantInfo" name="partQuantInfo[0]" style="width:3em" minlength="1" maxlength="1"></td>
<td><input type="text" class="form-control" id = "partInfo" name="partInfo[1]" style="width:5em" minlength="5" maxlength="5"></td>
<td><input type="number" class="form-control" id = "partQuantInfo" name="partQuantInfo[1]" style="width:3em" minlength="1" maxlength="1"></td>
</tr>`;
}
table += "</table>";
document.getElementById("tagsPartsTable").innerHTML = table;
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('input').on('blur', function() {
if ($("#partsQuantForm").valid()) {
$('#tagsParts').prop('disabled', false);
} else {
$('#tagsParts').prop('disabled', true);
}
});
jQuery("#partsQuantForm").validate({
rules: {
'partInfo[]': {
required: true,minlength: 5,maxlength: 5
},
'partQuantInfo[]': {
required: true,minlength: 2,maxlength: 2
}
}
});
});
</script>

How to storage data return from Aspnet MVC and filter it

I have a problem filtering the data returned from the server side. The idea is to store the list model and filter the data from the search inputs on that list. All this requires no data updates from the controller. I just want to filter it through the onlick event with the initial initialized list model. Is there a way to get this working with MVC. I am so familiar with react and angular.
In react I can do this:
var oldList = ...array;
array.filter(x => x.id === id && x.name === name)
Thanks for all the help!
Here is my code:
#model IEnumerable<Safetrac.Models.UserModel>
#{
ViewBag.Title = "User Page";
}
<script src="~/Scripts/filter.js"></script>
<div class="row">
<div class="container">
First name: <input type="text" id="firstName" />
SurName: <input type="text" id="surName" />
Email: <input type="text" id="email" />
Date Created: <input type="date" id="createdDate" />
<button type="button" class="btn-primary" onclick="Filter()">Filter</button>
<br />
</div>
</div>
<div class="row">
<div class="container">
<h2>Users Record</h2>
<div class="table-responsive">
<table class="table table-bordered table-condensed table-striped table-hover sortable">
<thead>
<tr class="danger">
<th data-firstsort="desc">Id</th>
<th data-firstsort="desc">Name</th>
<th data-firstsort="desc">Email</th>
<th data-firstsort="desc">Date Created</th>
</tr>
</thead>
#foreach (var item in Model)
{
<tr>
<td>#item.Id</td>
<td>#item.Name</td>
<td>#item.Email</td>
<td>#item.DateCreated</td>
</tr>
}
</table>
</div>
</div>
</div>
Onlick filter event:
//Function for getting the Data Based upon Employee ID
function Filter() {
var firstName = document.getElementById("id").value;
var surName = document.getElementById("name").value;
var email = document.getElementById("email").value;
var createdDate = document.getElementById("createdDate").value;
//filter here ?
}

When to use $ .each get duplicate values ​from the rows of a table

Good morning, I want to get all the records in a table and add them to an array and then register them to the database using ajax.
The problem I have is that using .each I get the values ​​of the first row correctly, but when adding another row, the array ends up duplicated.
I share some images so that my problem is better understood
debugging the first row of the table
duplicates
all duplicate table rows
Javascript
function AgregarLista() {
const TD = $('<td></td>');
const TR = $('<tr></tr>');
const TABLE_VENTA = $('#dtVenta');
const PRODUCT_TOTAL = $('#TotalPagar');
let item = 0;
$('#btnAgregarTabla').click(function () {
item++;
let id_cliente = $('#id_cliente').val();
let id_producto = $('#id_producto').select2('val');
let precio_producto = $('#precio').val();
let stock_producto = $('#stock').val();
let cantidad_producto = $('#cantidad').val();
let subtotal_producto = parseInt(precio_producto) * parseInt(cantidad_producto);
let nro_venta = TD.clone().html(item).addClass('nro_sale');
let cliente = TD.clone().html(id_cliente).addClass('td_customer');
let producto = TD.clone().html(id_producto).addClass('td_product');
let precio = TD.clone().html(precio_producto).addClass('td_price');
let stock = TD.clone().html(stock_producto).addClass('td_stock');
let cantidad = TD.clone().html(cantidad_producto).addClass('td_quantity');
let preciototal = TD.clone().html(subtotal_producto).addClass('subtotal');
let newRow = TR.clone().append(nro_venta, cliente, producto, precio, stock, cantidad, preciototal);
let total = subtotal_producto;
$('.subtotal').each(function (index, tr) {
total = total + parseInt($(this).text());
});
TABLE_VENTA.find('tbody').append(newRow);
PRODUCT_TOTAL.find('#total_pagar').val(total);
//*===========================================================
//* here I call the method I use to get the array
//* ==========================================================
loopDetailTable();
});
}
With this code I get the values ​​of the table rows
// * ==============================================
//* With this code I get the values ​​of the table rows
// * ==============================================
function loopDetailTable(params) {
let index = 0;
var obj = new Object();
obj.DetailsList = [];
$('#dtVenta').each(function () {
let item_detalle = new Object();
item_detalle.vNumero = $('.nro_sale').text();
item_detalle.cID = $('.td_customer').text();
item_detalle.pID = $('.td_product').text();
item_detalle.pPrice = $('.td_price').text();
item_detalle.pStock = $('.td_stock').text();
item_detalle.pQuantity = $('.td_quantity').text();
item_detalle.pSubtotal = $('.subtotal').text();
obj.DetailsList[index] = item_detalle;
index++;
console.log(obj);
});
return obj;
}
HTML form
<div class="d-flex">
<div class="col-md-5">
<form role="form">
<div class="card">
<div class="card-body">
<h5>Datos del cliente:</h5>
<div class="form-group d-flex">
<div class="col-md-6 d-flex">
<input type="text" name="dni" id="dni" class="form-control" placeholder="dni cliente">
<input type="button" id="btnBuscarCliente" value="Buscar" class="btn btn-outline-danger">
</div>
<div class="col-md-6">
<input type="hidden" name="id_cliente" id="id_cliente" value="">
<input type="text" name="nombre_cliente" id="nombre_cliente" value="" class="form-control" placeholder="Cliente" disabled>
</div>
</div>
<h5>Datos del producto:</h5>
<div class="form-group d-flex">
<div class="col-md-6 d-flex">
<!-- <input type="text" name="id_producto" id="id_producto" class="form-control" placeholder="codigo producto"> -->
<select name="id_producto" id="id_producto" class="id_producto js-states form-control"></select>
<input type="button" id="btnBuscarProducto" value="Buscar" class="btn btn-outline-danger">
</div>
<div class="col-md-6">
<input type="text" name="nombre_producto" id="nombre_producto" class="form-control" placeholder="Producto" disabled>
</div>
</div>
<div class="form-group row">
<div class="col-md-4">
<input type="text" name="precio" id="precio" class="form-control" placeholder="s/.0.00" disabled>
</div>
<div class="col-md-4">
<input type="number" name="stock" id="stock" class="form-control" placeholder="stock" disabled>
</div>
<div class="col-md-4">
<input type="number" name="cantidad" id="cantidad" value="1" class="form-control" placeholder="cantidad">
</div>
</div>
</div>
<div class="card-footer">
<input type="button" id="btnAgregarTabla" value="Agregar" class="btn btn-primary float-right">
</div>
</div>
</form>
</div>
<div class="col-md-7">
<div class="card">
<div class="card-body">
<div class="d-flex col-md-6 ml-auto">
<label class="mx-3 mt-1">Nro.serie:</label>
<input type="text" name="nro_serie" id="nro_serie" th:value="${serie}" class="form-control">
</div>
<table id="dtVenta" class="table mt-4" style="width: 100%;">
<thead>
<tr>
<th>Nro.Venta</th>
<th>Cliente</th>
<th>Producto</th>
<th>Precio</th>
<th>Stock</th>
<th>Cantidad</th>
<th>SubTotal</th>
<tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div id="TotalPagar" class="card-footer">
<div class="row">
<input type="button" id="btnCancelarVenta" value="Cancelar" class="btn btn-danger">
<input type="button" id="btnGenerarVenta" value="Generar" class="btn btn-success mx-1">
<div class="d-flex ml-auto">
<label for="" class="mx-2 mt-1">Total:</label>
<input type="text" name="total_pagar" id="total_pagar" class="form-control">
</div>
</div>
</div>
</div>
</div>
</div>
Thank you all for your help, greetings.
You get 'duplicates' because of the selector. You select using the class names, which are not unique. For example $('.td_customer').text(); select all customer cells.
Which you don't want. You want only the customer cell of a certain row.
I think you can solve your problem with iterating over the table rows (you iterate over the tables with id dtVenta, that's only one table).
So try something like:
$('#dtVenta tr').each(function () {
// $(this) is the 'current' row of the table
let item_detalle = new Object();
item_detalle.vNumero = $(this).find('.nro_sale').text(); // find all child .nro_sale cells and get it's text
item_detalle.cID = $(this).find('.td_customer').text();
item_detalle.pID = $(this).find('.td_product').text();
item_detalle.pPrice = $(this).find('.td_price').text();
item_detalle.pStock = $(this).find('.td_stock').text();
item_detalle.pQuantity = $(this).find('.td_quantity').text();
item_detalle.pSubtotal = $(this).find('.subtotal').text();
obj.DetailsList[index] = item_detalle;
index++;
console.log(obj);
});

need to create multiple groups using form in angular6

I need to create multiple groups in the form. when i create a childgroup and enter an input value the same value reflect in another group i known this is due to ngModel but how to overcome this issue. there is another issue i am facing under childGroup there is 2 table when i create another childGroup and add a new table row to that childGroup this will reflect in another childGroup also.
HTML
<fieldset *ngFor="let task of tasks; let a = index">
<legend>childGroup</legend>
<button (click)="deleteRow(a)" class="btn btn-sm btn-circle btn-danger actionMargin rmv-btn">X</button>
<div class="row">
<section class="col col-6">
<label class="label">Name</label>
<label class="input">
<input type="text" class="input-sm" [(ngModel)]="task.Name" name="task[a].Name" required>
</label>
</section>
<section class="col col-6">
<label class="label">Comm</label>
<label class="input">
<input type="text" class="input-sm" [(ngModel)]="task.Config.command" name="task[a].Config.command" required>
</label>
</section>
</div>
<!--Table-->
<section>
<h2>ABC</h2>
<table class="table table-bordered">
<thead>
<tr>
<th class="name">S no.</th>
<th class="name">Label</th>
<th class="name">Value</th>
<th class="name">Dynamic</th>
<th class="name">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of task.ports; let i = index">
<td align="center"><label>{{i + 1}}</label></td>
<td><input type="text" [(ngModel)]="item.Label" name="item[i].Label" [ngModelOptions]="{standalone: true}"
class="inputborder" required></td>
<td><input type="number" [disabled]="item[i].boolean" [(ngModel)]="item[i].Value" name="item.Value"
[ngModelOptions]="{standalone: true}" class="inputborder" required></td>
<td><input type="checkbox" [(ngModel)]="item[i].boolean" name="item[i].boolean" class="check"
[ngModelOptions]="{standalone: true}" required><span class="yes">Yes</span></td>
<td align="center"><button (click)="deleteRow(i,'port')" placement="top" tooltip="Remove Port" class="btn btn-sm btn-circle btn-danger actionMargin rmv-btn">X</button></td>
</tr>
</tbody>
</table>
<button type="button" (click)="Addrow('port')" placement="top" tooltip="Add Port" class="btn btn-sm btn-primary posi">Add
abc</button>
</section>
</fieldset>
TS.
tasks= [];
taskObj = { //click on a blue + button i am pushing this object to tasks
Name: "",
Config: {
command: ""
},
artifacts : [],
ports : []
};
// to add a table row
Addrow(i) {
if (i == 'port') {
let num = 0;
this.taskObj.ports.push({
Label: '',
Value: num,
boolean: true
});
} else {
this.taskObj.artifacts.push({
Source: '',
Relative: ''
})
}
console.log(this.tasks);
}
//remove the table row
deleteRow(index, i) {
if (i == "port") {
this.taskObj.ports.splice(index, 1);
} else {
this.taskObj.artifacts.splice(index, 1);
}
}
I the HTML code i have not add 'XYZ' table code because its same as 'ABC' table. how to implement validation to this loop within loop. Please help me with this issue.

document.getElementById() on a value that is set through a Meteor template

So I've been trying to build a website using Meteor and am quite new with it. I am trying to have javascript that will make use of the values on the page and then create a download from those values. These values differ depending on which page the user is on as the meteor template is loaded with specific information. The way I would think is would work is:
var thing = document.getElementById("tcpout").value;
but when I test this I get "undefined". Now if I don't do .value then do something like
console.log(document.getElementById("tcpout"));
the output in the console is this:
<td id="tcpout"> 50443</td>
where 50443 is the value that I want. Yet I can't seem to figure out how to get that into the javascript. I am using meteor and have tried a few things through meteor's project .js file, but can't seem to figure out how to incorporate dynamic fields into javascript. Essentially I just want to figure out the easiest and best way to work with the mongodb data on the client-side with javascript. Here is the template and the meteor js file.
<template name="profile">
{{#each iotdevice}}
<div class="container" style="margin-top:10px">
<div class="starter-template" align="center">
<h1>{{model}} {{manufacturer}} {{type}}</h1>
<p class="lead"></p>
<table class="table table-bordered">
<thead>
<tr>
<th>Ports</th>
<th>Outgoing</th>
<th>Incoming</th>
</tr>
</thead>
<tbody>
<tr>
<td>TCP</td>
<td id="tcpout"> {{tcpout}}</td>
<td id="tcpin"> {{tcpin}}</td>
</tr>
<tr>
<td>UDP</td>
<td id="udpout"> {{udpout}}</td>
<td id="udpin"> {{udpin}}</td>
</tr>
</tbody>
</table>
<table class="table table-bordered">
<thead>
<tr>
<th colspan="2">Domains</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{domains}}</td>
</tr>
</tbody>
</table>
</div>
<h4 align="center">Select Firewall</h4>
<div align="center">
<button style="margin-bottom:15px" type="button" class="btn btn-outline-danger" onclick="vyosformshow()">
VyOS
</button>
<button style="margin-bottom:15px" type="button" class="btn btn-outline-danger"
onclick="download('test.sh','hello\nworld')">IPTables
</button>
<button style="margin-bottom:15px" type="button" class="btn btn-outline-danger">FreePBX</button>
<button style="margin-bottom:15px" type="button" class="btn btn-outline-danger" onclick="dthings()">IPFire
</button>
<button style="margin-bottom:15px" type="button" class="btn btn-outline-danger">IPCop</button>
</div>
<div id="vyosform" style="display:none">
<form>
<div class="form-row">
<div class="form-group col-md-6">
<label for="exampleInputEmail1">firewall in name</label>
<input class="form-control" id="firein" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="exampleInputPassword1">firewall out name</label>
<input class="form-control" type="text" id="fireout" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="exampleInputPassword1">rule number</label>
<input class="form-control" id="rulenum" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="exampleInputPassword1">device IP address</label>
<input class="form-control" id="ip" placeholder="">
</div>
<div align="center">
<button id="dostuff" class="btn btn-primary" style="margin-bottom:30px">Submit</button>
</div>
</div>
</form>
</div>
</div>
{{/each}}
</template>
JS
if (Meteor.isClient) {
//this code only runs on the client
var directory = Iron.Location.get().path;
var start = directory.lastIndexOf("/");
var stop = directory.search(".html");
var parseddir = directory.slice(start + 1, stop);
var search = directory.slice(start + 1);
var regexsearch = new RegExp(["^", search, "$"].join(""), "i");
console.log(search);
Template.iotprofiler.helpers({
'device': function () {
return DeviceList.find();
}
});
Template.profile.helpers({
'iotdevice': function () {
return DeviceList.find({model: parseddir});
}
});
Template.search.helpers({
'results': function () {
return DeviceList.find({$or: [{model: regexsearch}, {manufacturer: regexsearch}, {type: z}]});
}
});
}

Categories

Resources