Jquery append new data to old ones has duplicate issue - javascript

How can I add new data to old ones without duplicate my tables?
logic
I select option, data returns in table
I select different option, data adds to old ones
Issue
When I do second part of my logic it add new table as well, meaning based on how many times i change my selected option it adds new tables.
Screenshot
when i select my first option having 1 table
when i select my second option having 2 tables
What I want
What I want is when i select my second/third etc. option image 2, only have 1 table include data of all those past and current options and not to make 1 table for each of them.
Code
HTML
<div class="mt-20 options"></div>
JavaScript
<script>
$(function(){
$('select[name="options"]').on('change', function() {
var addressID = $(this).val();
if(addressID) {
$.ajax({
url: '{{ url('admin/getoptions') }}/'+encodeURI(addressID),
type: "GET",
dataType: "json",
success:function(data) {
// $('div.options').empty();
$('div.options').append('<div class="mb-20"><h4>Check mark your needed options only</h4></div>'+
'<table id="table" class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th width="50" class="text-center">Check</th>'+
'<th class="text-center">Title</th>'+
'<th class="text-center">Price</th>'+
'</thead>'+
'<tbody></tbody>'+
'</table>');
// 2. Loop through all entries
var keys = ['title'];
data.forEach(function(row) {
var $row = $('<tr />');
$row.append('<td class="text-center" width="50"><label class="switch switch-small"><input type="checkbox" /><span><input class="form-control" type="text" name="optionID[]" value="'+row['id']+'"></span></label></td>');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$row.append('<td class="text-center"><input class="form-control" placeholder="if fill this price, the price will add to product price when user select it." type="number" name="optionPRICE[]"></td>');
$('#table tbody').append($row);
});
}
});
}else{
$('div.options').empty();
}
});
});
</script>
Any idea?

Here are the steps to take:
Remove the $('div.options').append( ... ) call
Add the following HTML to your static div element, and hide it with style="display:none":
<div class="mt-20 options" style="display:none">
<div class="mb-20"><h4>Check mark your needed options only</h4></div>
<table id="table" class="table table-bordered table-hover table-responsive">
<thead>
<th width="50" class="text-center">Check</th>
<th class="text-center">Title</th>
<th class="text-center">Price</th>
</thead>
<tbody>
</tbody>
</table>
</div>
Add code after the data.forEach loop, to unhide the div:
$('#table tbody').append($row);
}); // end of loop
$("div.options").show(); // <---

First you need to build your table once. But you are appending new tables every success call. That happens in the line:
$('div.options').append('<div class="mb-20">...
That append is actually creating the table and appending it to the div.
Instead you should create the table only one time before the success callback, then just update it with the new data.
$(function(){
var updateTable = function() {
var addressID = $(this).val();
var data = JSON.parse(addressID);
// show the table div
$('div.options').show();
// clear old rows
$('tbody', myTable).empty();
// 2. Loop through all entries
var keys = ['title'];
data.forEach(function(row) {
var $row = $('<tr />');
$row.append('<td class="text-center" width="50"><label class="switch switch-small"><input type="checkbox" /><span><input class="form-control" type="text" name="optionID[]" value="'+row+'"></span></label></td>');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$row.append('<td class="text-center"><input class="form-control" placeholder="if fill this price, the price will add to product price when user select it." type="number" name="optionPRICE[]"></td>');
$('tbody', myTable).append($row);
});
};
// create and save table for later manipulations
var myTable = $('<table class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th width="50" class="text-center">Check</th>'+
'<th class="text-center">Title</th>'+
'<th class="text-center">Price</th>'+
'</thead>'+
'<tbody></tbody>'+
'</table>');
// append h4
$('div.options').append('<div class="mb-20"><h4>Check mark your needed options only</h4></div>');
// append the table
$('div.options').append(myTable);
// select event
$('select[name="options"]').on('change', updateTable);
updateTable.call($('select[name="options"]').first());
});
{"d":4,"e":5,"f": 6}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="options">
<option value="[1,2,3]">Data1</option>
<option value="[4,5,6]">Data2</option>
</select>
<div class="options"></div>

Related

Jquery UI sortable not working for appended rows

I am trying to use jQuery UI to make a sortable table. It is working fine for the rows already added before the page load. However, I also have function to let users to add new rows, if they need.
jQuery UI sortable function not working for these appended rows.
HTML:
<button id="add" onclick="cloneRow()">Add row(s)</button>
<table id="testTable" class="table">
<thead>
<tr>
<th></th>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr id="rowFirst">
<td>#</td>
<td><input class="form-control" type="text" name="c1[]"></td>
<td><input class="form-control" type="text" name="c2[]"></td>
</tr>
<tr>
<td>#</td>
<td><input class="form-control" type="text" name="c1[]"></td>
<td><input class="form-control" type="text" name="c2[]"></td>
</tr>
</tbody>
</table>
JS:
function cloneRow() {
var rowAmount = document.getElementById("rowAmount").value;
var getTotalRows = $('table > tbody').children().length;
for (var i = -1; i < rowAmount - 1; i++) {
var row = document.getElementById("rowFirst"); // find row to copy
var table = document.getElementById("testTable"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newRow" + (getTotalRows + i); // change id or other attributes/contents
clone.classList.remove('hidden');
table.appendChild(clone); // add new row to end of table
$('#newRow' + (getTotalRows + i)).children().each(function() {
$(this).children().attr('id', $(this).children().attr('id') + (getTotalRows + i));
});
}
}
$("table tbody").sortable({});
https://jsfiddle.net/brkztrk/3odnr4t2/5/
As you can see first two rows are perfectly sortable, but rows appended by cloneRow() function are not sortable.
does anybody has any idea how to fix this?
Thanks a lot!
Consider the following: https://jsfiddle.net/Twisty/srm7fyo3/
JavaScript
function cloneRow() {
var rowAmount = $("#rowAmount").val();
for (var i = 0; i <= rowAmount; i++) {
var clone = $("#rowFirst").clone();
clone.attr("id", "new-row-" + $('table > tbody > tr').length);
clone.appendTo("table tbody");
$("table tbody").sortable("refresh");
}
}
$("table tbody").sortable({
items: "> tr",
handle: "td:eq(0)"
});
As new rows are created, the Sortable is refreshed. This way they each become a sortable item.

how to generate dynamic table

I have data with me , which is one dropdown data and one from textbox values which i generate dynamic and get the values.
now i want to generate the table from these value. I get values in alert but I struggling to generate the table
here is my code:
$('#save_skills').on("click",function(){
$('.importance option:selected').each(function(){
importance = $(this).text();
})
$('input.skill ').each(function() {
skill = $(this).val();
alert(skill);
});
$('#div_skills').append('<table class="table table-bordered"><tr><td>'+ skill +'</td><td>'+ importance +'</td></tr></table>')
});
I tried this but i get only last record, how to use for loop for below code, I am confused:
$('#div_skills').append('<table class="table table-bordered"><tr><td>'+ skill +'</td><td>'+ importance +'</td></tr></table>')
i generate this html dynamically:
$("#addSkills_link").on("click", function () {
$("#table_skills").
append('<tr><td><input type="text" class="form-control skill" id="new_skill" placeholder="Skills"></td><td><select class="form-control importance" id="ddl_skills"><option value="">Select importance</option><option value="">1</option><option value="">2</option><option value="">3</option><option value="">4</option><option value="">5</option><option value="">6</option><option value="">7</option><option value="">8</option><option value="">9</option><option value="">10</option></select></td>');
});
You need to join all values like,
var importance = [],skill=[];
$('#save_skills').on("click",function(){
$('.importance option:selected').each(function(){
importance.push($(this).text());
});
$('input.skill').each(function() {
skill.push($(this).val());
});
$('#div_skills').append('<table class="table table-bordered"><tr><td>'+ skill.join(', ') +'</td><td>'+ importance.join(', ') +'</td></tr></table>')
});
Updated, after the comment php | 8 and in second row: java | 9 your code should be like,
$('#save_skills').on("click",function(){
table = $('<table class="table table-bordered"></table>').appendTo($('#div_skills').empty())
$('input.skill').each(function(index) {
skill= $(this).val();
importance= $('.importance').eq(index).find('option:selected').text();
table.append('<tr><td>'+skill+'</td><td>'+importance+'</td></tr>');
});
});
#div_skills{border:1px solid #0cf}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table><tr><td><input type="text" class="form-control skill" id="new_skill" placeholder="Skills"></td><td>
<select class="form-control importance" id="ddl_skills"><option value="">Select importance</option><option value="">1</option><option value="">2</option><option value="">3</option><option value="">4</option><option value="">5</option><option value="">6</option><option value="">7</option><option value="">8</option><option value="">9</option><option value="">10</option></select></td></tr>
<tr><td><input type="text" class="form-control skill" id="new_skill" placeholder="Skills"></td><td>
<select class="form-control importance" id="ddl_skills"><option value="">Select importance</option><option value="">1</option><option value="">2</option><option value="">3</option><option value="">4</option><option value="">5</option><option value="">6</option><option value="">7</option><option value="">8</option><option value="">9</option><option value="">10</option></select></td></tr>
</table>
<div id="div_skills"></div>
<button id="save_skills">Save Skills</button>
Just add your table in your html like so :
<table class="table table-bordered" id="div_skills_table"></table>
And modify your script with this :
$('input.skill').each(function() {
skill = $(this).val();
$('#div_skills_table').append('<tr><td>'+ skill +'</td><td>'+ importance +'</td></tr>');
});
It will add a new row per skill

Update a HTML table record via jQuery

I have created a form with only three inputs, a HTML table and a submit button
<div class="form-group">
<input type="text" id="inputText1" required>
<input type="text" id="inputText2" required>
<input type="text" id="inputText3" required>
</div>
<button type="button" class="btn btn-default" id="submit">Submit</button>
</form>
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed" id="myTable" style="width:90%; margin:0 auto;">
<thead>
<tr>
<th>ID</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
that works this way:
every time the user clicks the submit button the HTML table adds to its rows the value of the inputs via jQuery + two linkbuttons and the variable cont specified as a number in a hidden element in order to easily locate the row when it comes to update it.
$(document).ready(function () {
var cont=0;
$("#submit").click(function(e) {
e.preventDefault();
cont++;
var id = $("#inputText1").val().toLowerCase();
var lastname = $("#inputText2").val();
var name = $("#inputText3").val();
if (checkId(lastname)) {
return alert('El ID ya ha sido especificado');
}
$('#myTable tbody').append('<tr><td for="id">' + id + '</td><td for="lastname">' + lastname + '</td><td>' + name + '</td><td id="cont" style="visibility:hidden">' + cont + '</td><td>Modificar Eliminar</td></tr>');
$("#inputText1").val('');
$("#inputText2").val('');
$("#inputText3").val('');
$('#inputText1').focus();
});
});
the submit button works OK the problem is when I want to modify a row, what I do now is to populate the inputs with the values of the row selected in order to let the user to modify its content but I cannot retrieve the value of the variable cont that represents an specific and different number for each row and besides of that I don't know how to update the table's row once the user decide to update the record, could you please help me, this is the jQuery code I had for the moment
$(document).ready(function () {
$("#myTable").on('click', '#select', function (e) {
e.preventDefault();
var currentRow = $(this).closest("tr");
//var contador= currentRow.$("#cont").val();
//alert(contador);
//doesn't retrieve neither show anything
var col1 = currentRow.find("td:eq(0)").text();
var col2 = currentRow.find("td:eq(1)").text();
var col3 = currentRow.find("td:eq(2)").text();
$("#inputText1").val(col1);
$("#inputText2").val(col2);
$("#inputText3").val(col3);
});
});
and also would like to dd that when the user add the info from the inputs to the table, theres a gap where the hidden field is
how could I solve this?

on click 'td' show input and when click to others 'td' restore its previous content

Below is my snippet, so what's going on below is, when click on any td then save its text to the variable named 'lttext' for later content restore and replace its content with a input that has a name equal to the 'th' text that has the same index to the currently click td and when click to other then restore the previously clicked td's previous content and to the current click td, clear the content and please an input and so to the others but seems unfortunately not working (check my snippet). Any ideas, clues, suggestions (to make it better)?
$(document).ready(function() {
var lttext;
$(document).on("click", "#uiu_table td:not(.ghost)", function() {
$(this).closest("tr").find(".editable").html("").text(lttext);
$(this).addClass("editable");
lttext = $(this).text();
$(this).text("").html('<input type="text" class="form-control" name="' + $(this).closest("table").find('th:eq(' + $(this).index() + ')').text().toLowerCase().toLowerCase().replace(/ /g, "_") + '" value="' + lttext + '"/>');
$(this).find("input").focus();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="extend clear table table-hover" id="uiu_table">
<thead>
<th class="text_align_left ghost">ID</th>
<th class="text_align_center">FIRSTNAME</th>
<th class="text_align_center">LASTNAME</th>
<th class="text_align_center">EMAIL</th>
<th class="text_align_center">MOBILE</th>
</thead>
<tbody>
<td class="text_align_left ghost">1</td>
<td class="text_align_center">Jano</td>
<td class="text_align_center">Gibis</td>
<td class="text_align_center">jano.gibis#yahee.com</td>
<td class="text_align_center">+6392023473</td>
</tbody>
</table>
NOTE: this is like a live table editing.

How to add to arraylist in javascript

I am using javascript for my server side validation.I need to add all data from a table which is dynamically generated while clicking an add button.
Clicking ADD button section is working fine.Also i added date picker to 2nd and 3rd columns.its working fine.The code is given below.....
function addRow(tableId) { //Add new row to given table having id tableId
var table = document.getElementById(tableId);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = '<input type="text" id="code'+ rowCount +'" name="code" maxlength="16"/>';
cell2.innerHTML = '<input type="text" id="datepicker2'+ rowCount +'" class="datepicker" name="validFrom" maxlength="50" >';
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
cell3.innerHTML = '<input type="text" id="datepicker3'+ rowCount +'" class="datepicker" name="validFrom" maxlength="50" >';
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
cell4.innerHTML = '<input type="button" id="del'+ rowCount +'" name="del" />';
Html code
<div class="systemsettings">
<h3><spring:message code="systemSetting.ratePeriods.label"/></h3>
</div>
<div class="systemset" >
<!-- table table-hover table-striped table-bordered table-highlight-head-->
<table id="systemsettingstid" class="table-bordered table-striped">
<thead class="tax_thead" id="tdDetailList">
<tr >
<!-- <th>Applicable From</th> -->
<th width="200" id="code" title="Code" >Code</th>
<th width="200" id="from" title="from ">from</th>
<th width="200" id="to" title="to">to</th>
<th width="50" id="del" title="del">del</th>
<!-- <th width="45" ><div class="add_new">
</div></th> -->
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div>
<tr>
<button type="button" onClick="javascript:addRow('systemsettingstid');">Add</button>
</tr>
</div>
DELETE BUTTON:
I have a delete button also appended inside the html code.
While clicking it the corresponding row should be deleted(fixed automatically while clicking add button on every row).
MY PROBLEM:
Adding and delete does not affect back end it just need to alter in an arraylist.
During final form submission the arraylist needs to go to backend(built in spring mvc).
1) Can we create an arraylist in javascript?
2) If we can how to add the text boxes and date picker details into arraylist?.
4) How to pass that arraylist in to my spring mvc controller?
NB:I am new to javascript.Any help will be highly appreciable.
<script>
var tdDetailList = [];
function init() {
var tdDetailTable = document.getElementById("tdDetailTable");
for (var i = 0, row; row = tdDetailTable.rows[i]; i++) {
var tdDetail = {code : row.cells[0].innerHTML, datepicker2 : row.cells[1].innerHTML, datepicker3 : row.cells[2].innerHTML};
tdDetailList.push(tdDetail);
}
alert(getDetailTableJson());
}
function deleteRow(index){
tdDetailList.splice(index, 1);
var tdDetailTable = document.getElementById("tdDetailTable");
tdDetailTable.deleteRow(index);
alert(getDetailTableJson());
}
function getDetailTableJson(){
return JSON.stringify(tdDetailList);
}
</script>
<body onload="init();">
<table id="tdDetailTable">
<tr><td>1</td><td>2</td><td>3</td><td>del</td></tr>
<tr><td>4</td><td>5</td><td>6</td><td>del</td></tr>
</table>
</body>
Can we create an arraylist in javascript?
Yes. In my example var tdDetailList = []; is array (list).
You can add elements to it:
tdDetailList.push(tdDetail);
and remove element in index: tdDetailList.splice(index, 1);
If we can how to add the text boxes and date picker details into arraylist?.
You can create object like:
var tdDetail = {code : row.cells[0].innerHTML, datepicker2 : row.cells[1].innerHTML, datepicker3 : row.cells[2].innerHTML};
with fields of your table and add the object to your list.
How to pass that arraylist in to my spring mvc controller?
Convert the list to json
JSON.stringify(tdDetailList);
In my example: "[{"code":"1","datepicker2":"2","datepicker3":"3"},{"code":"4","datepicker2":"5","datepicker3":"6"}]"
and send.
If you want to add and delete using JAVA SCRIPT then it will very complex and lengthy.
But using JQUERY it will work fine and easily you can handle ADD, DELETE actions also
use JQUERY and in this append and remove methods are there you can use it and insert a row in table and delete a row in table
May be you new in jQUERY but once you get it, its amazing than JAVA SCRIPT
Hope you getting let me know if you have any confusion. ['}

Categories

Resources