How To Get Right SrNo in Add remove Clone With My Calculation - javascript

How To Get Right SrNo in Add remove Clone With My Calculation
Click To Add(Multiple Time) After Delete Some Row After Re Click Add To Get SrNo Wrong And I Want With My Calculation...
<div id="button_pro">
<div id='input_1' class="row">
<div class="input-field col s1">
<input class="sno" type="text" name="Sr_1" value="1" >
<label for="Sr">Sr</label>
</div>
<div class="input-field col s2">
<input id="item_code" type="text" name="item_code_1" value=" ">
<label for="item_code">Item Code</label>
</div>
<div class="input-field col s2">
<input id="item_name" type="text" name="item_name_1" value=" ">
<label for="item_name">Item Name</label>
</div>
<div class="input-field col s1">
<input type="text" class="quantity" name="quantity_1" value=" ">
<label for="quantity">Quantity</label>
</div>
<div class="input-field col s1">
<input type="text" class="net_rate" name="net_rate_1" value=" ">
<label for="net_rate">Net Rate</label>
</div>
<div class="input-field col s1">
<input type="text" class="tax" name="tax_1" value=" ">
<label for="tax">tax</label>
</div>
<div class="input-field col s1">
<input type="text" class="Gross Rate" name="Gross Rate_1" value=" ">
<label for="Gross Rate">Gross Rate</label>
</div>
<div class="input-field col s1">
<input type="text" class="total" name="total_1" value=" " readonly>
<label for="total">total</label>
</div>
<div class="input-field col s2"> <i class="mdi-content-add">Add</i>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s8">
</div>
<div class="input-field col s2">
<input type="text" name="Grand" id="Grand" value=" ">
<label for="net_rate">Grand Total</label>
</div>
</div>
$('document').ready(function(){
var id=2,txt_box;
$('#button_pro').on('click','.add',function(){
$(this).remove();
txt_box='<div id="input_'+id+'" class="row"><div class="input-field col s1"><input type="text" name="Sr_'+id+'" value="'+id+'" ><label for="SrNo" class="active">SrNo</label></div><div class="input-field col s2"><input id="item_code" type="text" name="item_code_'+id+'"><label for="item_code" class="active">Item Code</label></div><div class="input-field col s2"><input id="item_name" type="text" name="item_name_'+id+'"><label for="item_name" class="active">Item Name</label></div><div class="input-field col s1"><input id="qty" type="text" name="quantity_'+id+'"><label for="quantity" class="active">Quantity</label></div><div class="input-field col s1"><input type="text" name="net_rate_'+id+'" ><label for="net_rate" class="active">Net Rate</label></div><div class="input-field col s1"><input type="text" name="tax_'+id+'" ><label for="tax"class="active">tax</label></div><div class="input-field col s1"><input type="text" name="Gross_Rate_'+id+'"><label for="Gross Rate" class="active">Gross Rate</label></div><div class="input-field col s1"><input type="text" name="total_'+id+'"><label for="total" class="active">total</label></div><div class="input-field col s2"><i class="mdi-content-add">Add</i></div><i class="mdi-content-clear">Remove</i></div>';
$("#button_pro").append(txt_box);
id++;
});
$('#button_pro').on('click','.remove',function(){
var parent=$(this).parent().prev().attr("id");
var parent_im=$(this).parent().attr("id");
$("#"+parent_im).slideUp('fast',function(){
$("#"+parent_im).remove();
if($('.add').length<1){
$("#"+parent).append('<div class="input-field col s2"> <i class="mdi-content-add">Add</i></div> ');
}
});
});
});
http://jsfiddle.net/p6jaxvzz/5/ Example For Problem

$('#button_pro').on('click', '.remove', function () {
var parent = $(this).parent().prev().attr("id");
var parent_im = $(this).parent().attr("id");
$("#" + parent_im).slideUp('fast', function () {
$("#" + parent_im).remove();
if ($('.add').length < 1) {
$("#" + parent).append('<div class="input-field col s2"> <i class="mdi-content-add">Add</i></div> ');
}
var $rows = $('.row');
$rows.each(function (i) {
if (i < $rows.length - 1) {
i++;
var $inputs = $('input', this);
$inputs.eq(0).attr('name', 'Sr_' + i).val(i);
$inputs.eq(1).attr('name', 'item_code_' + i);
$inputs.eq(2).attr('name', 'item_name_' + i);
$inputs.eq(3).attr('name', 'quantity_' + i);
$inputs.eq(4).attr('name', 'net_rate_' + i);
$inputs.eq(5).attr('name', 'tax_' + i);
$inputs.eq(6).attr('name', 'Gross_Rate_' + i);
$inputs.eq(7).attr('name', 'total_' + i);
}
});
id--;
});
});
Fiddle

This will surely help you. I have moddifed your sequence of elements in HTML too, but they are fine don't worry about that.
Here just showing you only for two fields, you add rest in var clone
JSFiddle
HTML
<div class="button_pro">
<div id='input_1' class="row">
<div class="input-field col s1">
<input class="sno" type="text" name="Sr_1" value="1">
<label for="Sr">Sr</label>
</div>
<div class="input-field col s2">
<input id="item_code" type="text" name="item_code_1" value=" ">
<label for="item_code">Item Code</label>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s2">
<a href="#" class="btn-floating waves-effect waves-light add ">
<i class="mdi-content-add">Add</i>
</a>
</div>
<div class="input-field col s2">
<a href="#" class="btn-floating waves-effect waves-light remove ">
<i class="mdi-content-add">Remove</i>
</a>
</div>
<div class="input-field col s8"></div>
<div class="input-field col s2">
<input type="text" name="Grand" id="Grand" value=" ">
<label for="net_rate">Grand Total</label>
</div>
</div>
JavaScript/JQuery
$(".remove").hide();
$(function () {
$(".add").click(function () {
num = $(".button_pro").length;
//alert(num);
if(num>=1)
{
$(".remove").show();
}
incr = num + 1;
var clone = '<div class="button_pro">';
clone += '<div id="input_' + incr + '" class="row">';
clone += '<div class="input-field col s1">';
clone += '<input class="sno" type="text" name="Sr_' + incr + '" value="' + incr + '">';
clone += '<label for="Sr">Sr</label>';
clone += '</div>';
clone += '<div class="input-field col s2">';
clone += '<input id="item_code" type="text" name="item_code_' + incr + '" value=" ">'
clone += '<label for="item_code">Item Code</label>'
clone += '</div>';
clone += '</div>';
clone += '</div>';
$(clone).insertBefore($(this).closest('.row'));
});
$(".remove").click(function () {
lastnum = $(".button_pro").length;
if(lastnum == 2)
{
$(".remove").hide();
}
$(".button_pro:nth-child(" + lastnum + ")").remove();
});
});

Related

Array returns as null in JS but "non-null" in GS

I'm attempting to use Apps Script and JS on a web app to retreive information stored in a google sheet, then output it to the webapp. However, I keep getting the error "cannot read property of null".
Problem is, when i run the apps script side of the code (as follows), my array is fine and when I log it to the console, it comes up no problem : code in snippit at end
When I run my code from the web app, I get the error. Here is the JS code : code in snippit at end
I've narrowed the error down to the last line of code, and to be more specific, the infoArray[i]. It just comes out as an array full of "null", even though when I run the GS code, it retruns the array as it should, with all the info as it is in the spreadsheet.
I've read at least 10 other threads, but still can't seem to figure out why this won't work. Any insight would be much appreciated !
Thank you
2ND EDIT WITH MRE (Sorry this is quite a long snippit. Both include-css files are empty for the moment, no use in the code themselves)
JavaScript
document.addEventListener('DOMContentLoaded', function() {
var elems2 = document.querySelectorAll('.autocomplete');
var instances2 = M.Autocomplete.init(elems2);
google.script.run.withSuccessHandler(populateWords).getNames();
})
document.getElementById('loadButton').addEventListener('click', clickGetInfo);
//FOR AUTOCOMPLETE
function populateWords(words) {
var autocomplete = document.getElementById("autoEmployee");
var instances = M.Autocomplete.init(autocomplete, {
data: words
});
}
function clickGetInfo() {
var employeeInfo = {};
employeeInfo.name = document.getElementById('autoEmployee').value;
google.script.run.withSuccessHandler(updateText).getInfoEdit(employeeInfo);
}
function updateText(infoArray) {
var elements = ["matricule", "sexe", "civ", "nom", "prenom", "nomJf", "birthday", "nationalite", "adresse", "codePostal", "ville", "pays", "communeNais", "paysNais", "dptNais", "numerosecu", "email",
"telephone", "shop", "contrat", "hhebdo", "dateDebut", "periodeEssais", "dateFin", "tuteur", "poste", "statut", "echelon", "salaire", "iban", "bic", "domiciliation",
"primeTel", "primeFroid", "comment", "rqth", "commentRqth", "titreSejour", "numeroTitre", "dateExpiration", "dateIngestion"
];
for (var i = 0; i < elements.length; i++) {
// console.log(document.getElementById(elements[i]).value);
// console.log(infoArray);
document.getElementById(elements[i]).value = infoArray[i];
}
}
GS
//common vars
var id = '1Sq6f68fjnF3qPfi6guWlSHT84f_UjcFFMnAXwKsqQkM'; // data base
//VARIABLES PAGE HTML
var Route = {};
Route.path= function(route,callback){
Route[route] = callback;}
// doGet + routes
function doGet(e) {
Route.path("pageEditEmployee",loadEdit);
if(Route[e.parameter.v]){
return Route[e.parameter.v]();
}else{
return HtmlService.createTemplateFromFile("home").evaluate();}}
// load edit page
function loadEdit(){
var tmp = HtmlService.createTemplateFromFile("pageEditEmployee");
return tmp.evaluate();
}
//CREATION DE LA FONCTION INCLUDE HTML
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();}
function getInfoEdit(employeeInfo) {
var ss = SpreadsheetApp.openById(id);
var wsData = ss.getSheetByName("DATA");
var data = wsData.getDataRange().getValues();
var infoArray = new Array();
var matricule = employeeInfo.name;
Logger.log(matricule);
for (var i = 0; i < data.length; i++) {
if (data[i][41] == matricule) {
//[41] for column AP
var row = i + 1; // row of data
Logger.log(row);
}
}
for (var i = 1; i < 42; i++) {
infoArray.push(wsData.getRange(row, i).getValue()); // push data into array
}
return infoArray; // return the array
}
// names for AUTOCOMPLETE FOR EDIT PAGE
function getNames() {
var ss = SpreadsheetApp.openById(id);
var wsData = ss.getSheetByName("DATA");
var lastRow = wsData.getRange("A1").getDataRegion().getLastRow();
var listOfNames = wsData.getRange(2, 42, lastRow - 1, 1).getValues();
var obj = Object.fromEntries(
// create object from array
listOfNames.map((name) => [name, null])
);
return obj;
}
HTML EDIT PAGE
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<?!= include("pageEditEmployee-css");?>
</head>
<body>
<div class="container">
<div class="row"></div>
<nav>
<div class="nav-wrapper lime">
<a class="brand-logo right">Espace RH</a>
<ul id="nav-mobile" class="left hide-on-med-and-down">
<li><i class="material-icons left">home</i>Home</li>
</ul>
</div>
</nav>
<div class="container">
<!-- DIV CONTAINER 1 -->
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix">textsms</i>
<input type="text" id="autoEmployee" class="autocomplete">
<label for="autoEmployee">Take your pick</label>
</div>
<div class="input-field col s6">
<button id="loadButton" class="btn waves-effect waves-light" type="submit" name="action">Load
<i class="material-icons right">check_circle</i>
</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s3">
<input disabled value="Matricule" id="matricule" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Civilité" id="civ" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Sexe" id="sexe" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Nom" id="nom" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Prénom" id="prenom" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Nom Jeune Fille" id="nomJf" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Date de Naissance" id="birthday" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Nationalité" id="nationalite" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Adresse" id="adresse" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Code Postal" id="codePostal" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Ville" id="ville" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Pays" id="pays" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Commune de Naissance" id="communeNais" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Pays de Naissance" id="paysNais" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Département de Naissance" id="dptNais" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Numéro de sécurité sociale" id="numerosecu" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Email" id="email" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Téléphone" id="telephone" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Atelier" id="shop" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Type de contrat" id="contrat" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Heures Hebdo" id="hhebdo" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Date de début" id="dateDebut" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s3">
<input disabled value="Fin de la période probatoire" id="periodeEssais" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Fin contrat si CDD" id="dateFin" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Tuteur ou Tutrice" id="tuteur" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Poste" id="poste" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Statut" id="statut" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Echelon" id="echelon" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Salaire" id="salaire" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="IBAN" id="iban" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="BIC" id="bic" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Domiciliation" id="domiciliation" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Prime de téléphone" id="primeTel" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Prime froid" id="primeFroid" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Commentaires primes" id="comment" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="RQTH" id="rqth" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Commentaires RQTH" id="commentRqth" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Titre de séjour" id="titreSejour" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Numéro de titre" id="numeroTitre" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Date expiration" id="dateExpiration" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Date d'enregistrement de la personne" id="dateIngestion" type="text" class="validate">
</div>
</div>
</div>
<!-- END DIV CONTAINER 1 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<?!= include("pageEditEmployee-js");?>
<div class="container">
<footer class="page-footer light-green darken-4 s12">
<div class="footer-copyright lime">
<div class="container black-text">
</div>
</div>
</footer>
</div>
</body>
</html>
HTML home page
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<?!= include("home-css");?>
</head>
<body>
<div class="container">
<div class="row"></div>
<nav>
<div class="nav-wrapper lime">
<a class="brand-logo right"></a>
<ul id="nav-mobile" class="left hide-on-med-and-down">
<li><i class="material-icons left">home</i>Accueil</li>
</ul>
</div>
</nav>
<div class="row"></div>
<h3 class="card-panel z-depth-3 white-text light-green darken-4">Hello, world</h3>
<div class="row"></div>
<div class="row"><!-- 1ERE LIGNE -->
<div class="col s6 m6">
<div class="card horizontal">
<div class="card-image">
<i class="large material-icons">access_time</i>
</div>
<div class="card-stacked">
<div class="card-content">
<p>My problem is in here</p>
</div>
<div class="card-action">
<a class="green-text" href="<?= ScriptApp.getService().getUrl();?>?v=pageEditEmployee">Click me</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div><!-- CLOSE CONTAINER -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="container">
<footer class="page-footer light-green darken-4 s12">
<div class="footer-copyright lime">
<div class="container black-text">
</div>
</div>
</footer>
</div>
</body>
</html>
Trying out your MRE I was getting completely different errors from you. But it was helpful to at least understand what you are trying to do.
What I believe the issue is:
Requests fail if you attempt to pass a Date, Function, DOM element besides a form, or other prohibited type, including prohibited types inside objects or arrays.
Parameters and return values - Google Documentation
Within your data is Date objects, so this will return null. I think this is the error you are getting.
Solution
So here is a minimal reproducible example, showing how to get your data as an array into the front-end.
Code.gs
function doGet(){
return HtmlService.createHtmlOutputFromFile("index")
}
function getInfo() {
let file = SpreadsheetApp.getActive();
let sheet = file.getSheetByName("Sheet1");
let range = sheet.getDataRange();
let values = range.getValues();
return JSON.stringify(values);
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Hello</h1>
<button id=main>Run</button>
<script>
function main(){
google.script.run.withSuccessHandler(handleInfo).getInfo()
}
function handleInfo(info){
console.log(JSON.parse(info))
}
const mainButton = document.getElementById("main")
mainButton.addEventListener('click', () => main())
</script>
</body>
</html>
Pressing the button in the web page results in this in the console:
Main change:
On the return value from Apps Script (server)
JSON.stringify([YOUR ARRAY OR OBJECT WITH DATES]);
Then when you recieve it in the front-end:
JSON.parse([YOUR ARRAY OR OBJECT WITH DATES])
References
JSON Object
Client-Server communication
Try this:
function getInfoEdit(employeeInfo) {
var ss = SpreadsheetApp.openById(id);
var dsh = ss.getSheetByName('DATA');
var data = dsh.getDataRange().getValues()
var infoArray = [];
var matricule = employeeInfo.name;
for (var i = 0; i < data.length; i++) {
if (data[i][41] == matricule) { //[41] for column AP column 42
infoArray.push(data[i]);//This pushes the entire row in to your output array
}
}
return (infoArray); // return the array
}
Can't confirm any of this because you did not supply the html but there are only 41 elements in the array below. I believe that you have 42 columns
function updateText(infoArray){
var elements = ["matricule","sexe", "civ", "nom", "prenom", "nomJf", "birthday", "nationalite", "adresse", "codePostal", "ville", "pays", "communeNais", "paysNais", "dptNais", "numerosecu", "email",
"telephone", "shop", "contrat", "hhebdo", "dateDebut", "periodeEssais", "dateFin", "tuteur", "poste", "statut", "echelon", "salaire", "iban", "bic", "domiciliation",
"primeTel", "primeFroid", "comment", "rqth", "commentRqth", "titreSejour", "numeroTitre", "dateExpiration","dateIngestion"];
for (var i = 0;i<elements.length;i++){
document.getElementById(elements[i]).value = infoArray[i];
}
}

Autocomplete form fields on dynamically created ones

I have been trying solutions for similar problems for hours now, all I could find is autocomplete for one field.
Here is my form code:
<div class="row form-group">
<label>1</label>
<div class="col col-sm-1"><input type="text" id="code1" name="code[]" placeholder="Code" class="form-control" required></div>
<div class="col col-sm-4"><input type="text" id="id2" name="product[]" placeholder="Produit" class="form-control" required></div>
<div class="col col-sm-1"><input type="text" id="id3" name="package[]" placeholder="Cdt" class="form-control" required></div>
<div class="col col-sm-1"><input type="text" id="id4" name="qte[]" placeholder="Qté" class="form-control" required></div>
<div class="col col-sm-1"><input type="text" id="id5" name="price[]" placeholder="Prix Unit" class="form-control" required></div>
<div class="col col-sm-1"><input type="text" id="id6" name="vat[]" placeholder="TVA" class="form-control" required></div>
<div class="col col-sm-1"><input type="text" id="id7" name="lot[]" placeholder="Lot" class="form-control" required></div>
<div class="col col-sm-1"><input type="text" id="id8" name="ddp[]" placeholder="DDP" class="form-control" required></div>
<div onclick="addRow(this.form);"><i class="btn-sm btn-primary fa fa-plus-circle"></i></div>
</div>
And here is the javascript to autocomplete + add rows:
var rowNum = 1;
function addRow(frm) {
rowNum ++;
var row = '<div class="row form-group" id="rowNum'+rowNum+'">'+
'<label>'+rowNum+'</label>'+
'<div class="col col-sm-1"><input type="text" id="code1" name="code[]" placeholder="Code" class="form-control" required></div>'+
'<div class="col col-sm-4"><input type="text" id="id2" name="product[]" placeholder="Produit" class="form-control" required></div>'+
'<div class="col col-sm-1"><input type="text" id="id3" name="package[]" placeholder="Cdt" class="form-control" required></div>'+
'<div class="col col-sm-1"><input type="text" id="id4" name="qte[]" placeholder="Qté" class="form-control" required></div>'+
'<div class="col col-sm-1"><input type="text" id="id5" name="price[]" placeholder="Prix Unit" class="form-control" required></div>'+
'<div class="col col-sm-1"><input type="text" id="id6" name="vat[]" placeholder="TVA" class="form-control" required></div>'+
'<div class="col col-sm-1"><input type="text" id="id7" name="lot[]" placeholder="Lot" class="form-control" required></div>'+
'<div class="col col-sm-1"><input type="text" id="id8" name="ddp[]" placeholder="DDP" class="form-control" required></div>'+
'<div onclick="removeRow('+rowNum+');"><i class="btn-sm btn-danger fa fa-minus-circle"></i></div>'+
'<div onclick="addRow(this.form);"><i class="btn-sm btn-primary fa fa-plus-circle"></i></div>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
And:
var mySource = [{"label":"7545","id2":"Product 001","id3":"50","id5":"3850.00","id6":"19"},
{"label":"9071","id2":"Product 002","id3":"1","id5":"103867.13","id6":"0"},
{"label":"6701","id2":"Product 003","id3":"50","id5":"2556.3","id6":"17"}];
$("#code1").autocomplete({
source: mySource,
select: function(event, ui){
if(ui.item){
$("#id2").val(ui.item.id2);
$("#id3").val(ui.item.id3);
$("#id5").val(ui.item.id5);
$("#id6").val(ui.item.id6);
return ui.item.label;
}
else{
$("#id2").val('');
$("#id3").val('');
$("#id5").val('');
$("#id6").val('');
}
},
change: function(event, ui){
if(ui.item){
$("#id2").val(ui.item.id2);
$("#id3").val(ui.item.id3);
$("#id5").val(ui.item.id5);
$("#id6").val(ui.item.id6);
}
else{
$("#id2").val('');
$("#id3").val('');
$("#id5").val('');
$("#id6").val('');
}
}
});
Autocomplete is only working on the first row. But not the dynamically added rows!
Any idea how I can enable autocomplete on newly added rows too?
You are using same ids for mutliple elements first change them to class . Then , change $("#code1") to $(".code1") then inside select & change function use $(this).closest(".form-group") to refer div where autocomplete is present and use .find() to get required inputs and add values there .
Next , when you add new elements you need to initialize your autocomplete . So, use jQuery('#itemRows .form-group:last .code1').autocomplete(options); this will get last form-group which is added and then get .code1 intialize it .
Lastly , to remove div when - is clicked use jQuery(rnum).closest(".form-group").remove(); where rnum refer to current element which is clicked then using closest remove entire div.
Demo Code :
var mySource = [{
"label": "7545",
"id2": "Product 001",
"id3": "50",
"id5": "3850.00",
"id6": "19"
},
{
"label": "9071",
"id2": "Product 002",
"id3": "1",
"id5": "103867.13",
"id6": "0"
},
{
"label": "6701",
"id2": "Product 003",
"id3": "50",
"id5": "2556.3",
"id6": "17"
}
];
var rowNum = 1
//use like this ..because mutliple places
var options = {
source: mySource,
select: function(event, ui) {
var selector = $(this).closest(".form-group") //here get closest form-group
if (ui.item) {
//find required inputs and then add value there
selector.find(".product").val(ui.item.id2);
selector.find(".package").val(ui.item.id3);
selector.find(".price").val(ui.item.id5);
selector.find(".vat").val(ui.item.id6);
return ui.item.label;
} else {
selector.find(".product").val('');
selector.find(".package").val('');
selector.find(".price").val('');
selector.find(".vat").val('');
}
},
change: function(event, ui) {
var selector = $(this).closest(".form-group")
if (ui.item) {
selector.find(".product").val(ui.item.id2);
selector.find(".package").val(ui.item.id3);
selector.find(".price").val(ui.item.id5);
selector.find(".vat").val(ui.item.id6);
} else {
selector.find(".product").val('');
selector.find(".package").val('');
selector.find(".price").val('');
selector.find(".vat").val('');
}
}
}
function addRow(frm) {
rowNum++;
//remove ids .. add classes
var row = '<div class="row form-group" id="rowNum' + rowNum + '">' +
'<label for="codes">' + rowNum + '</label>' +
'<div class="col col-sm-1"><input type="text" name="code[]" placeholder="Code" class="form-control code1" required></div>' +
'<div class="col col-sm-4"><input type="text" name="product[]" placeholder="Produit" class="form-control product" required></div>' +
'<div class="col col-sm-1"><input type="text" name="package[]" placeholder="Cdt" class="form-control package" required></div>' +
'<div class="col col-sm-1"><input type="text" name="qte[]" placeholder="Qté" class="form-control qty" required></div>' +
'<div class="col col-sm-1"><input type="text" name="price[]" placeholder="Prix Unit" class="form-control price" required></div>' +
'<div class="col col-sm-1"><input type="text" name="vat[]" placeholder="TVA" class="form-control vat" required></div>' +
'<div class="col col-sm-1"><input type="text" name="lot[]" placeholder="Lot" class="form-control lot" required></div>' +
'<div class="col col-sm-1"><input type="text" name="ddp[]" placeholder="DDP" class="form-control ddp" required></div>' +
'<div onclick="removeRow(' + rowNum + ');"><i class="btn-sm btn-danger fa fa-minus-circle"></i></div>' +
'<div onclick="removeRow(this);"><i class="btn-sm btn-primary fa fa-plus-circle">-</i></div>';
jQuery('#itemRows').append(row);
//get last added form-group in that code1 initialize it ..
jQuery('#itemRows .form-group:last .code1').autocomplete(options);
}
function removeRow(rnum) {
jQuery(rnum).closest(".form-group").remove(); //remove closest form-group
var index = 1;
//rstart id and count
$("#itemRows .form-group").each(function() {
index++;
$(this).attr("id", "rowNum" + index);
$(this).find("label[for=codes]").text(index)
})
rowNum--; //decremnt count...
}
$(".code1").autocomplete(options);
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="row form-group">
<label>1</label>
<div class="col col-sm-1"><input type="text" id="code1" name="code[]" placeholder="Code" class="form-control code1" required></div>
<div class="col col-sm-4"><input type="text" id="id2" name="product[]" placeholder="Produit" class="form-control product" required></div>
<div class="col col-sm-1"><input type="text" id="id3" name="package[]" placeholder="Cdt" class="form-control package" required></div>
<div class="col col-sm-1"><input type="text" id="id4" name="qte[]" placeholder="Qté" class="form-control" required></div>
<div class="col col-sm-1"><input type="text" id="id5" name="price[]" placeholder="Prix Unit" class="form-control price" required></div>
<div class="col col-sm-1"><input type="text" id="id6" name="vat[]" placeholder="TVA" class="form-control vat" required></div>
<div class="col col-sm-1"><input type="text" id="id7" name="lot[]" placeholder="Lot" class="form-control lot" required></div>
<div class="col col-sm-1"><input type="text" id="id8" name="ddp[]" placeholder="DDP" class="form-control ddp" required></div>
<div onclick="addRow(this.form);"><i class="btn-sm btn-primary fa fa-plus-circle">+</i></div>
</div>
<div id="itemRows">
</div>

How to store the data from a dynamic table to database

I'm trying to figure out how to store the data from a dynamic table to the database.
Here's the idea: I'm developing a system to control the drivers journey. It basically will store the day work of the driver, spliting it on differente intervals, such as: Driving time, meal time, waiting time, etc (all of them in HH:MM). They will be adding in different tables, as the following picture shows.
Journey Control
The input data (hour), for each table, can be different. It will depend on the driver's day journey. I need to catch and store those hours on a database.
My best idea is to get all those hours after the user ends the input, but how do I store that if I don't have the field's name?
Additional information: I'm using Java, SpringBoot and Thymeleaf to develop it.
JourneyControl.RegisterHourJourney = (function() {
var counterDriving = 0;
var counterInterval = 0;
var counterMeal = 0;
var counterWaiting = 0;
var counterRest = 0;
function RegisterJourneyHour() {
this.novaDrivingBtn = $('.js-add-new-direcao');
this.novoIntervalBtn = $('.js-add-new-intervalo');
this.novaMealBtn = $('.js-add-new-refeicao');
this.novaWaitingBtn = $('.js-add-new-espera');
this.novoRestBtn = $('.js-add-new-pernoite');
this.deleteDrivingBtn = $('#direcaot');
this.deleteIntervalBtn = $('#intervalot');
this.deleteMealBtn = $('#refeicaot');
this.deleteWaitingBtn = $('#esperat');
this.deleteRestBtn = $('#pernoitet');
}
RegisterHourJourney.prototype.start = function() {
this.novaDrivingBtn.on('click', onAdicionarHourDriving.bind());
this.novoIntervalBtn.on('click', onAdicionarHourInterval.bind());
this.novaMealBtn.on('click', onAdicionarHourMeal.bind());
this.novaWaitingBtn.on('click', onAdicionarHourWaiting.bind());
this.novoRestBtn.on('click', onAdicionarHourRest.bind());
this.deleteDrivingBtn.on('click', '.js-delete-btn',
onDeleteHourDriving.bind());
this.deleteIntervalBtn.on('click', '.js-delete-btn',
onDeleteHourInterval.bind());
this.deleteMealBtn.on('click', '.js-delete-btn',
onDeleteHourMeal.bind());
this.deleteWaitingBtn.on('click', '.js-delete-btn',
onDeleteHourWaiting.bind());
this.deleteRestBtn.on('click', '.js-delete-btn',
onDeleteHourRest.bind());
}
function onAdicionarHourDriving() {
/*var newRow = $("<tr id=\" " + + counterDriving + " \">");*/
var newRow = $("<tr>");
var cols = "";
var inputInicio = $('#inicioDirecao').val();
var inputFim = $('#fimDirecao').val();
var direcao = $('#direcao').val();
if (!inputInicio || !inputFim) {
alert('Os campos início e fim devem ser preenchidos.');
} else if (inputInicio.length != 5 || inputFim.length != 5) {
alert('Preencha as horas corretamente (HH:MM).');
} else {
cols += '<td>' + inputInicio + '</td>';
cols += '<td>' + inputFim + '</td>';
cols += '<td class="text-center"><a class=" btn btn-link btn-xs js-tooltip js-delete-btn" title="Delete" href="#" ><i class="glyphicon glyphicon-remove"></i></a></td>';
newRow.append(cols);
$("#direcaot").append(newRow);
counterDriving++;
$('#inicioDirecao').val('');
$('#fimDirecao').val('');
}
}
function onAdicionarHourInterval() {
var newRow = $("<tr>");
var cols = "";
var inputInicio = $('#inicioIntervalo').val();
var inputFim = $('#fimIntervalo').val();
if (!inputInicio || !inputFim) {
alert('Os campos início e fim devem ser preenchidos.');
} else if (inputInicio.length != 5 || inputFim.length != 5) {
alert('Preencha as horas corretamente (HH:MM).');
} else {
cols += '<td>' + inputInicio + '</td>';
cols += '<td>' + inputFim + '</td>';
cols += '<td class="text-center"><a class="btn btn-link btn-xs js-tooltip js-delete-btn" title="Delete" href="#" ><i class="glyphicon glyphicon-remove"></i></a></td>';
newRow.append(cols);
$("#intervalot").append(newRow);
counterInterval++;
$('#inicioIntervalo').val('');
$('#fimIntervalo').val('');
}
}
function onAdicionarHourMeal() {
var newRow = $("<tr>");
var cols = "";
var inputInicio = $('#inicioRefeicao').val();
var inputFim = $('#fimRefeicao').val();
if (!inputInicio || !inputFim) {
alert('Os campos início e fim devem ser preenchidos.');
} else if (inputInicio.length != 5 || inputFim.length != 5) {
alert('Preencha as horas corretamente (HH:MM).');
} else {
cols += '<td>' + inputInicio + '</td>';
cols += '<td>' + inputFim + '</td>';
cols += '<td class="text-center"><a class="btn btn-link btn-xs js-tooltip js-delete-btn" title="Delete" href="#" ><i class="glyphicon glyphicon-remove"></i></a></td>';
newRow.append(cols);
$("#refeicaot").append(newRow);
counterMeal++;
$('#inicioRefeicao').val('');
$('#fimRefeicao').val('');
}
}
function onAdicionarHourWaiting() {
var newRow = $("<tr>");
var cols = "";
var inputInicio = $('#inicioEspera').val();
var inputFim = $('#fimEspera').val();
if (!inputInicio || !inputFim) {
alert('Os campos início e fim devem ser preenchidos.');
} else if (inputInicio.length != 5 || inputFim.length != 5) {
alert('Preencha as horas corretamente (HH:MM).');
} else {
cols += '<td>' + inputInicio + '</td>';
cols += '<td>' + inputFim + '</td>';
cols += '<td class="text-center"><a class="btn btn-link btn-xs js-tooltip js-delete-btn" title="Delete" href="#" ><i class="glyphicon glyphicon-remove"></i></a></td>';
newRow.append(cols);
$("#esperat").append(newRow);
counterWaiting++;
$('#inicioEspera').val('');
$('#fimEspera').val('');
}
}
function onAdicionarHourRest() {
var newRow = $("<tr>");
var cols = "";
var inputInicio = $('#inicioPernoite').val();
var inputFim = $('#fimPernoite').val();
if (!inputInicio || !inputFim) {
alert('Os campos início e fim devem ser preenchidos.');
} else if (inputInicio.length != 5 || inputFim.length != 5) {
alert('Preencha as horas corretamente (HH:MM).');
} else {
cols += '<td>' + inputInicio + '</td>';
cols += '<td>' + inputFim + '</td>';
cols += '<td class="text-center"><a class="btn btn-link btn-xs js-tooltip js-delete-btn" title="Delete" href="#" ><i class="glyphicon glyphicon-remove"></i></a></td>';
newRow.append(cols);
$("#pernoitet").append(newRow);
counterRest++;
$('#inicioPernoite').val('');
$('#fimPernoite').val('');
}
}
function onDeleteHourDriving() {
var item = document.activeElement;
item.closest("tr").remove();
counterDriving -= 1;
}
function onDeleteHourInterval() {
var item = document.activeElement;
item.closest("tr").remove();
counterInterval -= 1;
}
function onDeleteHourMeal() {
var item = document.activeElement;
item.closest("tr").remove();
counterMeal -= 1;
}
function onDeleteHourWaiting() {
var item = document.activeElement;
item.closest("tr").remove();
counterWaiting -= 1;
}
function onDeleteHourRest() {
var item = document.activeElement;
item.closest("tr").remove();
counterRest -= 1;
}
return RegisterHourJourney;
}());
$(function() {
var RegisterHourJourney = new JourneyControl.RegisterHourJourney();
RegisterHourJourney.start();
});
<body>
<section layout:fragment="conteudo">
<div class="page-header">
<div class="container-fluid">
<div class="row">
<div class="col-xs-10">
<h1>Journey Control</h1>
<!-- <h1 th:if="${empresa.nova}">Cadastrar jornada</h1> -->
<!-- <h1 th:unless="${empresa.nova}" th:text="|Editar empresa - ${empresa.razaoSocial}|">Editar jornada</h1> -->
</div>
<div class="col-xs-2">
<div class="aw-page-header-controls">
<!-- <a class="btn btn-default" th:href="#{/empresas}"> -->
<a class="btn btn-default">
<i class="glyphicon glyphicon-plus-sign"></i>
<span class="hidden-xs hidden-sm">Search Journey</span>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<!-- <form method="POST" th:object="${jornada}" class="form-vertical js-form-loading"
th:action="${empresa.nova} ? #{/empresas/nova} : #{/empresas/{codigo}(codigo=${empresa.codigo})}"> -->
<form class="form-vertical js-form-loading">
<!-- <cj:message/> -->
<!-- <input type="hidden" th:field="*{codigo}" /> -->
<div class="row">
<div class="col-sm-2 form-group field-required">
<label for="data" class="control-label">Date</label>
<input id="data" type="text" class="form-control js-date" />
</div>
<div class="col-sm-5 form-group field-required">
<label for="motorista" class="control-label">Driver</label>
<input id="motorista" type="text" class="form-control" autofocus="autofocus" />
</div>
<div class="col-sm-1 form-group">
<label class="control-label">Day off</label>
<div>
<input type="checkbox" class="js-status" data-size="small" data-off-color="danger"
data-on-text="Yes" data-off-text="No" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-7 form-group">
<fieldset class="fieldset-border">
<legend class="legend-border">Driving Time</legend>
<div class="form-group row">
<!-- <label for="inicioDirecao" class="col-sm-1 col-form-label">Start</label> -->
<label for="inicioDirecao" class="col-sm-1 col-form-label">Start</label>
<div class="col-sm-3">
<input id="inicioDirecao" type="text" class="form-control js-hora">
<input type="hidden" value="DIRECAO"/>
</div>
<label for="EndDirecao" class="col-sm-1 col-form-label">End</label>
<div class="col-sm-3">
<input id="EndDirecao" type="text" class="form-control js-hora">
<input type="hidden" value="DIRECAO"/>
</div>
<div class="form-group col-sm-2">
<button type="button" class="btn btn-primary js-add-new-direcao">Add</button>
</div>
</div>
<div class="form-group row">
<div class="table-responsive bw-tabela-simples col-sm-10">
<table class="table table-hover">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th></th>
</tr>
</thead>
<tbody id="direcaot">
</tbody>
</table>
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-sm-7 form-group">
<fieldset class="fieldset-border">
<legend class="legend-border">Driving Interval</legend>
<div class="form-group row">
<label for="inicioIntervalo" class="col-sm-1 col-form-label">Start</label>
<div class="col-sm-3">
<input id="inicioIntervalo" type="text" class="form-control js-hora">
<input type="hidden" value="INTERVALO"/>
</div>
<label for="EndIntervalo" class="col-sm-1 col-form-label">End</label>
<div class="col-sm-3">
<input id="EndIntervalo" type="text" class="form-control js-hora">
<input type="hidden" value="INTERVALO"/>
</div>
<div class="form-group col-sm-2">
<button type="button" class="btn btn-primary js-add-new-intervalo">Add</button>
</div>
</div>
<div class="form-group row">
<div class="table-responsive bw-tabela-simples col-sm-10">
<table class="table table-hover">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th></th>
</tr>
</thead>
<tbody id="intervalot">
</tbody>
</table>
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-sm-7 form-group">
<fieldset class="fieldset-border">
<legend class="legend-border">Meal</legend>
<div class="form-group row">
<label for="inicioRefeicao" class="col-sm-1 col-form-label">Start</label>
<div class="col-sm-3">
<input id="inicioRefeicao" type="text" class="form-control js-hora">
<input type="hidden" value="REFEICAO"/>
</div>
<label for="EndRefeicao" class="col-sm-1 col-form-label">End</label>
<div class="col-sm-3">
<input id="EndRefeicao" type="text" class="form-control js-hora">
<input type="hidden" value="REFEICAO"/>
</div>
<div class="form-group col-sm-2">
<button type="button" class="btn btn-primary js-add-new-refeicao">Add</button>
</div>
</div>
<div class="form-group row">
<div class="table-responsive bw-tabela-simples col-sm-10">
<table class="table table-hover">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th></th>
</tr>
</thead>
<tbody id="refeicaot">
</tbody>
</table>
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-sm-7 form-group">
<fieldset class="fieldset-border">
<legend class="legend-border">Waiting Time</legend>
<div class="form-group row">
<label for="inicioEspera" class="col-sm-1 col-form-label">Start</label>
<div class="col-sm-3">
<input id="inicioEspera" type="text" class="form-control js-hora">
<input type="hidden" value="ESPERA"/>
</div>
<label for="EndEspera" class="col-sm-1 col-form-label">End</label>
<div class="col-sm-3">
<input id="EndEspera" type="text" class="form-control js-hora">
<input type="hidden" value="ESPERA"/>
</div>
<div class="form-group col-sm-2">
<button type="button" class="btn btn-primary js-add-new-espera">Add</button>
</div>
</div>
<div class="form-group row">
<div class="table-responsive bw-tabela-simples col-sm-10">
<table class="table table-hover">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th></th>
</tr>
</thead>
<tbody id="esperat">
</tbody>
</table>
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-sm-7 form-group">
<fieldset class="fieldset-border">
<legend class="legend-border">Rest</legend>
<div class="form-group row">
<label for="inicioPernoite" class="col-sm-1 col-form-label">Start</label>
<div class="col-sm-3">
<input id="inicioPernoite" type="text" class="form-control js-hora">
<input type="hidden" value="PERNOITE"/>
</div>
<label for="EndPernoite" class="col-sm-1 col-form-label">End</label>
<div class="col-sm-3">
<input id="EndPernoite" type="text" class="form-control js-hora">
<input type="hidden" value="PERNOITE"/>
</div>
<div class="form-group col-sm-2">
<button type="button" class="btn btn-primary js-add-new-pernoite">Add</button>
</div>
</div>
<div class="form-group row">
<div class="table-responsive bw-tabela-simples col-sm-10">
<table class="table table-hover">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th></th>
</tr>
</thead>
<tbody id="pernoitet">
</tbody>
</table>
</div>
</div>
</fieldset>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Salvar</button>
</div>
</form>
</div>
</section>
<th:block layout:fragment="javascript-extra">
<script th:src="#{/javascripts/jornada.mascara-horas.js}"></script>
<script th:src="#{/javascripts/vendors/bootstrap-switch.min.js}"></script>
<script th:src="#{/javascripts/cadastro_jornada.js}"></script>
<script>
$('.js-status').bootstrapSwitch();
</script>
</th:block>
</body>
An example for meals:
When you add a new row, give it a name in the way of name="meal[" + nextMeal + "]", this nomenclature will map your new meal to a list of meals in the controller on form submission.
To know what's the proper value for nextMeal, do something like this:
var nextMeal = 0;
while($("tr[name='nextMeal[" + nextMeal + "]']").length){
nextMeal++;
}

how can i capture multiple form inputs and save in an array

<template name="uploadTicket">
<div class="row">
<h3> Upload Ticket</h3>
<form class="ticket-form col s12" enctype="multipart/form-data">
<div class="row">
<div class="input-field col s12">
<input id="name" type="text" class="validate">
<label for="name">Event Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="location" type="text" class="validate">
<label for="location">Location</label>
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input id="date" type="date" class="validate">
<label for="date"></label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<textarea id="description" class="materialize-textarea"></textarea>
<label for="Description">Description</label>
</div>
</div>
<div class="row">
<div class="col s6">
<h5>More Price Fields</h5>
</div>
<div class="col s6">
<a class="btn-floating btn-large waves-effect waves-light red" id="addField"><i class="mdi mdi-plus"></i></a>
</div>
</div>
<div class="wrapper">
<div class="row">
<div class="input-field col s4">
<input name="priceClass[]" type="text" class="validate">
<label for="priceClass[]">Class</label>
</div>
<div class="input-field col s4">
<input name="priceAmount[]" type="text" class="validate">
<label for="priceAmount[]">Price</label>
</div>
<div class="input-field col s4">
<h6>Input Price Classes and Amounts.</h6>
</div>
</div>
<br>
</div>
<br>
<div class="row">
<div >
<button class="waves-effect waves-light btn" type="submit">Upload</button>
</div>
</div>
</form>
</div>
</template>
This is my Template
Template.uploadTicket.events({
'click #addField': function (event) {
event.preventDefault();
var max_fields = 10;
var wrapper = $(".wrapper");
var add_button = $(".addField");
var x = 1;
if (x < max_fields)
{
x++; //text box increment
$(wrapper).append(' <div class="row"> <div class="input-field col s4"> <input name="priceClass[]" type="text" class="validate"> <label for="priceClass[]">Class</label> </div> <div class="input-field col s4"> <input name="priceAmount[]" type="text" class="validate"> <label for="priceAmount[]">Price</label> </div> <a class="btn-floating btn-large waves-effect waves-light red" id="removeField"><i class="mdi mdi-minus"></i></a></div> <br>'); //add input box
}
$(wrapper).on("click","#removeField", function(e)
{ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
}
});
This is my JavaScript for that template. I am giving the user option to add multiple fields so that they can have different classes for prices. Like gold class for a certain amount, VIP for another amount ,regular for another amount and so on. I am having a problem with how to get those input values when submitting the values and saving them into an array.
You would use jquery to loop through your inputs and send their values into an empty array. Then take the array with data and send it to your collection.
let valueStore = [];
console.log(valueStore) // an empty array
$('.input-field input').each(function(){
if (this.value != ''){
valueStore.push(this.value)
}
})
console.log(valueStore) // will have your values.
You can use JQuery-Selectors to get all Input Fields. You allready gave them a class. After that you can extract all necessary information into your array.
The JQuery-Selector should look something like:
$('.input-field')
Use a forEach loop to get every selected element.

add/remove all textbox id increment

How to Set Add/remove in all text-box id Auto increment (ItemCode,ItemName Add To +1 And Remove to -1.)
<div id="mainDiv">
<div class="one">
<div class="row">
<div class="input-field col s1">
<input type="text" id="sno" class="sno" name="Sr[]" value="1" >
<label for="Sr" >Sr</label>
</div>
<div class="input-field col s2">
<input id="ItemCode" type="text" name="ItemCode[]" onKeyUp="showHint(this.value)">
<label for="ItemCode" >Item Code</label>
</div>
<div class="input-field col s2">
<input id="ItemName" type="text" name="ItemName[]" value=" ">
<label for="ItemName" >Item Name</label>
</div>
<div class="input-field col s1 add">
Add
</div>
<div class="input-field col s1 delete">
Remove
</div>
</div>
</div>
</div>
$(document).ready(function () {
$(".add").click(function () {
var length = $('.one').length;
var cloned = $(this).closest('.one').clone(true);
cloned.appendTo("#mainDiv").find('.sno').val(length + 1);
cloned.find(':input:not(".sno")').val(" ");
var parent = $(this).closest('.one');
});
$('.delete').click(function () {
if($('.one').length==1){
alert("This is default row and can't deleted");
return false;
}
var parent = $(this).closest('.one');
$(this).parents(".one").remove();
// reset serial numbers again
$('.sno').each(function(i){
this.value=i+1;
})
});
});
https://jsfiddle.net/Nilesh_Patel/05e3wtcm/1/ here example
try to add this code to your add event
cloned.find('input[name="ItemCode[]"]').attr('id','ItemCode'+(length + 1));
cloned.find('input[name="ItemName[]"]').attr('id','ItemName'+(length + 1));
Here is what you can do. This will reset the id's on delete as well.
Since the for attribute of the labels should be bound to the inputs id you may want to change those as well.
$(document).ready(function () {
$(".add").click(function () {
var length = $('.one').length;
var cloned = $(this).closest('.one').clone(true);
cloned.appendTo("#mainDiv").find('.sno').val(length + 1);
cloned.find(':input:not(".sno")').val(" ");
cloned.find("label[for*='ItemCode']").attr('for', 'ItemCode' + (length+1));
cloned.find("input[id*='ItemCode']").attr('id', 'ItemCode' + (length+1));
cloned.find("label[for*='ItemName']").attr('for', 'ItemName' + (length+1));
cloned.find("input[id*='ItemName']").attr('id', 'ItemName' + (length+1));
var parent = $(this).closest('.one');
});
$('.delete').click(function () {
if($('.one').length==1){
alert("This is default row and can't deleted");
return false;
}
var parent = $(this).closest('.one');
$(this).parents(".one").remove();
$('.one').each(function(index, item) {
$(this).find('.sno').val(index+1);
$(this).find("label[for*='ItemCode']").attr('for', 'ItemCode' + (index+1));
$(this).find("input[id*='ItemCode']").attr('id', 'ItemCode' + (index+1));
$(this).find("label[for*='ItemName']").attr('for', 'ItemName' + (index+1));
$(this).find("input[id*='ItemName']").attr('id', 'ItemName' + (index+1));
});
});
});
<div id="mainDiv">
<div class="one">
<div class="row">
<div class="input-field col s1">
<input type="text" id="sno" class="sno" name="Sr[]" value="1" />
<label for="Sr" >Sr</label>
</div>
<div class="input-field col s2">
<input id="ItemCode" type="text" name="ItemCode[]" onKeyUp="showHint(this.value)" />
<label for="ItemCode" >Item Code</label>
</div>
<div class="input-field col s2">
<input id="ItemName" type="text" name="ItemName[]" value=" " />
<label for="ItemName" >Item Name</label>
</div>
<div class="input-field col s1 add">
Add
</div>
<div class="input-field col s1 delete">
Remove
</div>
</div>
</div>
</div>
You can reset the serial numbers using the following function. check the jsfiddle https://jsfiddle.net/05e3wtcm/4/
function ResetSerialNumbers(){
$('.sno').each(function(i){
var val = i+1;
this.value=val;
$(this).closest('.row').find("input[id^='ItemCode']").first().attr("id",'ItemCode'+val);
$(this).closest('.row').find("input[id^='ItemName']").first().attr("id",'ItemName'+val);
});
}

Categories

Resources