How to retain add rows and its value even after page reload - javascript

Good day,
I have a table where you can dynamically add/remove rows, on each row you can add an select an item from the list its working perfectly at the moment, what I want to add is for it to retain the added rows and its values even if I page reload my browser?
I have seen on my research that you can attain it by using cookies/localStorage,but would be okay if I store many items on it?
heres my table looks like:
my JS:
function addRow(){
var rowCount = document.getElementById('tblItemList').rows.length - 1 ;
var rowArrayId = rowCount ;
var toBeAdded = document.getElementById('toBeAdded').value;
if (toBeAdded=='')
{ toBeAdded = 2; }
else if(toBeAdded>10)
{
toBeAdded = 10;
}
for (var i = 0; i < toBeAdded; i++) {
var rowToInsert = '';
rowToInsert = "<tr><td><input id='itemName"+rowArrayId+"' required name='product["+rowArrayId+"][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' />"+
"<input type='hidden' class='rowId' value='"+rowArrayId+"'>"+
"<input type='hidden' name='product[" + rowArrayId + "][itemId]' id='itemId'></td>";
$("#tblItemList tbody").append(
rowToInsert+
"<td><textarea readonly name='product["+rowArrayId+"][description]' class='form-control description' rows='1' ></textarea></td>"+
"<td><input type='number' min='1' max='9999' name='product["+rowArrayId+"][quantity]' class='qty form-control' required />"+
"<input id='poItemId' type='hidden' name='product[" + rowArrayId + "][poContentId]'></td>"+
"<td><input type='number' min='1' step='any' max='9999' name='product["+rowArrayId+"][price]' class='price form-control' required /></td>"+
"<td class='subtotal'><center><h3>0.00</h3></center></td>"+
"<input type='hidden' name='product["+rowArrayId+"][delete]' class='hidden-deleted-id'>"+
"<td class='actions'><a href='#' class='btnRemoveRow btn btn-danger'>x</a></td>"+
"</tr>");
var rowId = "#itemName"+rowArrayId;
$(rowId).select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
formatNoMatches: function( term ) {
$('.select2-input').on('keyup', function(e) {
if(e.keyCode === 13)
{
$("#modalAdd").modal();
$(".select2-input").unbind( "keyup" );
}
});
return "<li class='select2-no-results'>"+"No results found.<button class='btn btn-success pull-right btn-xs' onClick='modal()'>Add New Item</button></li>";
},
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
rowArrayId = rowArrayId + 1;
};
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
$(".qty, .price").bind("keyup change", calculate);
};
the problem here is whenever Im refreshing the page the Items that I added will also be lost as well as those rows that I've added, any suggestions please? Thanks you very much for your time! Have a nice Day!

Your best bet here would be to cookies to store json data.
Your best bet here would be to cookies to store json data.
function storeRowData() {
var data = [];
$('.TABLE_NAME tr').each(function () {
var $this = $(this),
pname = $this.find(PRODUCT_NAME_INPUT).val(),
desc = $this.find(PRODCUT_DESC_INPUT).val(),
quant = $this.find(PRODUCT_QUANTITY_INPUT).val(),
price = $this.find(PRODUCT_PRICE_INPUT).val();
var temp = { productName: pname, description: desc, quantity: quant, price: price };
data.push(temp);
});
$.cookie('Table_Rows', JSON.stringify(data), {OPTIONS});
}
Now whenever you add or remove rows, you can call this. And when you reload page just read the cookie and parse the string back to JSON and traverse and call addrow for each row.
NOTE: Be sure to read full documentation on jquery.cookie() Here

You can use window.location.reload(true) and $( document ).ready function where you can get current no. of rows.Define row count & column count variable as a global variable.
location.reload(true);
var rowCount,rowArrayId,toBeAdded ;
$(document).ready(function() {
rowCount= document.getElementById('tblItemList').rows.length - 1 ;
rowArrayId = rowCount ;
toBeAdded = document.getElementById('toBeAdded').value;
});

Related

how to add rows based upon checkbox checked and delete rows based on unchecked in jquery

This is code i have written to get checkbox value and add rows
can anyone have look on this and find what's the problem with this code
$('.dm_list_data').on('change', function() {
var $sel = $(this);
val = $(this).val();
$opts = $sel.children();
prevUnselected = $sel.data('unselected');
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
var currSelected = $('.dm_list_data').val();
var post_data = {
'deliver_id': currSelected
}
console.log(post_data);
$.ajax({
type: "POST",
url: base_url + 'curriculum/topicadd/get_deliver_method_details',
data: post_data,
datatype: "JSON",
success: function(msg) {
var JSONObject = JSON.parse(msg);
JSONObject.forEach(function(element) {
var delivery_mtd_name = element.delivery_mtd_name;
var ftfl_hours = element.ftfl_hours;
var assessment_hours = element.assessment_hours;
var slt_hours = element.slt_hours;
var markup = "<tr><td><input type='text' name='record' value='" + delivery_mtd_name + "'></td><td><input type='text' name='record' value='" + ftfl_hours + "'></td><td><input type='text' name='record' value='" + assessment_hours + "'></td><td><input type='text' name='record' value='" + slt_hours + "'></td></tr>";
$("table tbody").append(markup);
});
}
});
});
Rows are getting multipe if i checked thrice please go through image
I will suggest create a hashmap which contains checked elements. Triggering Onchange will just update your hashmap and call a function to create/delete rows. hashmaps are way faster and easy to code.Make your keys as id of table row. Depending on check or uncheck condition, call function which is required.
Before you create a new element and append, just check whether it exists. If does not exist, then add it. Just add id for text box and if condition. Below code may have syntax error, i just tested in browser. Maybe little tweaks needed.
$('.dm_list_data').on('change', function() {
var $sel = $(this);
val = $(this).val();
$opts = $sel.children();
prevUnselected = $sel.data('unselected');
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
var currSelected = $('.dm_list_data').val();
var post_data = {
'deliver_id': currSelected
}
console.log(post_data);
$.ajax({
type: "POST",
url: base_url + 'curriculum/topicadd/get_deliver_method_details',
data: post_data,
datatype: "JSON",
success: function(msg) {
var JSONObject = JSON.parse(msg);
JSONObject.forEach(function(element) {
var delivery_mtd_name = element.delivery_mtd_name;
var ftfl_hours = element.ftfl_hours;
var assessment_hours = element.assessment_hours;
var slt_hours = element.slt_hours;
if($('#'+delivery_mtd_name).length==0)///added this line
{
//updated below line
var markup = "<tr><td><input type='text' name='record' value='" + delivery_mtd_name + "' id='" + delivery_mtd_name + "'></td><td><input type='text' name='record' value='" + ftfl_hours + "'></td><td><input type='text' name='record' value='" + assessment_hours + "'></td><td><input type='text' name='record' value='" + slt_hours + "'></td></tr>";
$("table tbody").append(markup);
}
});
}
});
});

how to insert dynamic multiple rows textboxes generated value in a variable

I'm trying insert dynamic multiple rows textboxes generated value in a variable to send it through ajax json to server side.
Code for generating multiple dynamic values.
$('#btnASize').click(function() {
var sizerangeMin = "<input type='text' ID='SizeMin' value='2.00' />";
var ToleranceMin = "<input type='text' ID='TolMin'+i value='1' />";
var ToleranceMax = "<input type='text' ID='TolMax'+i value='1' />";
var markup = "<tr><td>" + sizerangeMin + "</td><td>" + ToleranceMin + "</td><td>" + ToleranceMax + "</td></tr>";
$("#WireDimTbl tbody").append(markup);
});
$('#btnASizeR').click(function() {
var sizerangeMin = "<input type='text' ID='SizeMin' value='2.00' />";
var sizerangeMax = "<input type='text' ID='SizeMax' value='3.00' />";
var ToleranceMin = "<input type='text' ID='TolMin' value='1' />";
var ToleranceMax = "<input type='text' ID='TolMax' value='1' />";
var markup = "<tr><td>" + sizerangeMin + "</td><td>" + sizerangeMax + "</td><td>" + ToleranceMin + "</td><td>" + ToleranceMax + "</td></tr>";
$("#WireDimTbl tbody").append(markup);
});
$('#btnWdDelete').click(function() {
$("#WireDimTbl tbody>tr:last").remove();
})
Ajax code for sending data
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function() {
$(document).on("click", "[id*=btnFrmSubmit]", function() {
var user = {};
user.PRODUCT_ID = 1;
user.TDC_NO = $("[id*=Tdc_No]").val();
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: JSON.stringify({
user: user
})
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Data has been added successfully.");
window.location.reload();
},
error: function(response) {
alert(response.responseText);
}
});
});
});
</script>
In the above ajax method i want to store values of dynamically generated multiple textboxes value in "var user" to send it through ajax method to server side but not getting any idea how to achieve it i have shown in above code only for a particular input box
"<th class='text-center'>TDC No.</th>" +
"<th><input id='Tdc_No' type='text' value='7y'/></th>".
how to achieve it for multiple dynamically generated input textboxes.
Code at server side i am just showing few items how am i doing.
public class User
{
public decimal PRODUCT_ID { get; set; }
public string TDC_NO { get; set; }
.
.
}
[WebMethod]
public static void SaveFrmDetails(User user)
{
string connectionString = ConfigurationManager.ConnectionStrings["condb"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO TDC_PRODUCT1(TDC_NO) VALUES (:TDC_NO)",con)
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue(":TDC_NO", user.TDC_NO);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
try like this , make use of .serializeArray() and find()
$( "#target" ).click(function() {
alert(JSON.stringify($("#WireDimTbl tbody").find(":input").serializeArray()));
});
jsfiddle working : https://jsfiddle.net/pranayamr/odja5te0/

Calculating Table Rows

So I have a table that i'm able to add a new row. If I manually type in the quantity and the price, the total is calculated using this javascript code.
function addRow() {
addTableRow($('.table tbody'));
}
function removeRow() {
var par = $(this).parent().parent();
var tableSize = $('.table tbody tr').length;
if(tableSize == '1'){
alert('You must have one row');
return false;
}
par.remove();
};
function calculateRow() {
var par = $(this).parent().parent();
var price = $(par).find('.price').val();
var qty = $(par).find('.qty').val();
var total = price*qty;
$(par).find('.total').val(total.toFixed('2'));
}
$('.table tbody').on("click", ".removeRow", removeRow);
$('.table tbody').on("blur", ".qty", calculateRow);
function addTableRow(table) {
$(table).append(
"<tr>" +
"<td><input name='item_number[]' type='text' class='id form-control'></td>" +
"<td><input name='item_name[]' type='text' class='name search form-control'></td>" +
"<td><input name='item_price[]' type='text' class='price form-control price'></td>" +
"<td><input name='item_qty[]' type='text' class='form-control qty'></td>" +
"<td><input name='item_total[]' type='text' class='form-control total'></td>" +
"<td class='text-center' style='vertical-align:middle;'><a href='#' class='text-success removeRow'><i class='fa fa-trash-o'></i></a></td>" +
"</tr>");
auto();
}
Now I've added Jquery UI AutoSuggest to my table and made it so I was able to fill the item number, item name, item quantity, and item price all by choosing a product. Using the javascript below:
function auto() {
var ac_config = {
source: "/admin/items/fetch_items",
select: function(event, ui){
var item = ui.item;
if(item) {
$(".id").val(item.id);
$(".price").val(item.price);
$(".qty").val('1');
var par = $(".qty").parent().parent();
var price = $(par).find('.price').val();
var qty = $(par).find('.qty').val();
var total = price*qty;
$(par).find('.total').val(total.toFixed('2'));
}
},
minLength: 1,
};
$(".search").autocomplete(ac_config);
}
Now as you can see, I am needing to calculate the row total and fill it. As the code sits above, the initial row that is by default made by html is calculated correctly. But once I add a new row and try to autofill it and calculate the total, the first row changes along with the new row I just added.
How do I get the javascript to run on the row I just autofilled with the jQuery UI?
use a class like selected on the active row and add some highlighting css based on that class.
function addRow() {
var $table = $('.table tbody');
addTableRow($table);
$table.find('tr.selected').removeClass('selected').end().find('tr:last').addClass('selected');
}
Now within the autocomplete callback you can target the selected row with your selectors
var ac_config = {
source: "/admin/items/fetch_items",
select: function(event, ui){
var item = ui.item;
if(item) {
var $row = $('tr.selected');
$row.find(".id").val(item.id);
$row.find(".price").val(item.price);
/* ....... etc....*/
}
},
minLength: 1,
};
Then somewhere in your initialization code add a click handler to toggle selected on row click:
$('.table tbody').on('click', 'tr',function(){
$(this).siblings().removeClass('selected');
$(this).addClass('selected');
});
I don't exactly understand your question.
But is this usefull for you?
With jquery you can each tr the and acumulate the values of each row
function total() {
var total=0;
$.each("table tr", function(key,row) {
var tr=$(this);
var qty=parseFloat(tr.find(".qty).val());
var price=parseFloat(tr.find(".price).val());
total+=qty*price;
});
return total;
}
$(".qty, .price").change(function(){
var total=total();
$(".total").html(total);
});

Increment In my Jquery No Working Fine?

i wanna increment hidden field value append in jquery but its not incrementing just printing "2" when i print value beforing initializing it to hidden field my code is,
<script type="text/javascript">
var k=0,j=0;
$(document).ready(function () {
$("#btnAdd").click(function () {
var field = $("#field").val();
var DDL_fromProfession="<select name='ParametersFromProf' id='DDL_FromProYear'>";
for(var i=1950;i<2012;i++)
{
DDL_fromProfession +="<option text='"+i+"' value='"+i+"'>"+i+"</option>";
}
DDL_fromProfession +="</select>";
var DDL_ToProfession="<select name='ParametersToProf' id='DDL_ToProYear'>";
for(var i=1950;i<2012;i++)
{
DDL_ToProfession +="<option text='"+i+"' value='"+i+"'>"+i+"</option>";
}
DDL_ToProfession +="</select>";
k+=1;
var newRow1="<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+DDL_fromProfession +" to "+DDL_ToProfession +"</td></tr>"
+"<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+"<input type='checkbox' name='chkbx_CurrPro"+k+"' value='Yes'>I currently work here</input>"
+"<input type='hidden' id='hide' name='hidden' value='"+k+"'></input>";
// alert(document.getElementByName("valPro").value);
//alert($('input').attr('hidden'));
//alert($('input#hide').val());
var input = "<input name='parameters' id='field' type='text' />";
var input1="<input name='parametersCompany' id='field' type='text'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " +input1 +"</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
var value = parseInt($(":hidden[name='hidden']").val()) + 1;
alert(value);
});
});
</script>
Hidden Field:
+"<input type='hidden' id='hide' name='hidden' value='"+k+"'></input>";
Printing Value:
var value = parseInt($(":hidden[name='hidden']").val()) + 1;
alert(value);
Hopes for your suggestion
I think you want the hidden value(:hidden[name='hidden']) = 2 (value writtent in alert)?
Then you must write a line after var value = parseInt($(":hidden[name='hidden']").val()) + 1; => $(":hidden[name='hidden']").val(value);
In this case your hidden value is 1 as you can test by alert(parseInt($(":hidden[name='hidden']").val()))

Problem with jquery

I creating jquery code to generate specific html-blocks that contains html-controls (e.g. textbox, textarea, button) with two buttons - add new block and delete current block:
$(document).ready(function () {
// Constants
var SEPARATOR = "`";
var SEPARATOR_START = "<span class='Hidden'>";
var SEPARATOR_END = "</span>";
var SEPARATOR_BLOCK = SEPARATOR_START + SEPARATOR + SEPARATOR_END;
var CONTAINER = "#weContainer";
// Initialize container
InitializeDataContainer(CONTAINER);
// Buttons events
$(".AddBlock").click(function () {
AddBlock(CONTAINER);
});
$(".DeleteBlock").click(function () {
DeleteBlock(CONTAINER, GetParentId(this));
});
// Functions
function GetParentId(container) {
var id = ($(container).parent().attr("id")).replace(new RegExp("_", 'g'), "");
return id;
}
function Template() {
var uniqueId = Math.random() * 10000000;
var template = "<div class='weBlock' id='_" + uniqueId + "_'>";
template += "<input type='button' value='add' class=\"AddBlock\" />";
template += "<input type='button' value='del' class=\"DeleteBlock\" />";
template += "<br/>";
template += "<input type='text' class='weStartDate weTextbox' />";
template += " ";
template += "<input type='text' class='weEndDate weTextbox' />";
template += "<br/>";
template += "<input type='text' class='weCompany weTextbox' />";
template += " ";
template += "<input type='text' class='weJobTitle weTextbox' />";
template += "<br/>";
template += "<input type='text' class='weClients weTextbox' />";
template += " ";
template += "<input type='text' class='weProjectName weTextbox' />";
template += "<br/>";
template += "<textarea type='text' rows='4' cols='40' class='weProjectDesc weTextarea'></textarea>";
template += "<br/>";
template += "<textarea type='text' rows='6' cols='40' class='weActivities weTextarea'></textarea>";
template += "<br/>";
template += "<textarea type='text' rows='4' cols='40' class='weToolsTech weTextarea'></textarea>";
template += "</div>";
template += SEPARATOR_BLOCK;
return template;
}
function GetIdFromTemplate(template) {
var array = template.split('_');
return array[1];
}
function AddBlock(container) {
$(container).append(Template());
}
function DeleteBlock(container, id) {
var content = $(container).html();
content = content.replace(new RegExp("\<span class='Hidden'\>", "g"), "")
.replace(new RegExp("\</span\>", "g"), "");
var blocks = content.split(SEPARATOR);
content = "";
var index;
for (var i = 0; i < blocks.length; i++) {
if (GetIdFromTemplate(blocks[i]) != id && !IsNullOrEmpty(blocks[i])) {
content += blocks[i] + SEPARATOR_BLOCK;
}
else {
index = i;
}
}
$(container).html(content);
}
function IsNullOrEmpty(string) {
if (string == null || string == 'undefined' || string.length == 0) {
return true;
}
else {
return false;
}
}
function InitializeDataContainer(container) {
$(container).html(Template());
}
});
For the first time (when page load) i created first block:
function InitializeDataContainer(container) {
$(container).html(Template());
}
My problem is next - buttons Add and Delete work only for this first html-block that i created when page load, but if i add new blocks in page using Add button (from this first block that works) then buttons Add and Delete from this new blocks doesn't work!
Sorry for may be not good code, im not javascript engineer:)
Use the .live() instead:
$(".AddBlock").live("click", function () {
AddBlock(CONTAINER);
});
And same for the other class - the .click() is "static" only for the elements that exists in the time of calling it, while .live() should work for any existing or future elements.
Your jQuery code adds event handlers to the Add/Delete buttons you create uses click to do so:
$(".AddBlock").click(function () {
AddBlock(CONTAINER);
});
This only affects HTML elements that are already in the page.
One solution would be to change it to
$(".AddBlock").live('click', function () {
AddBlock(CONTAINER);
});
to make it also work for elements that get added to the page later.
Another solution would be to manually add the click event handlers to any elements you add to the page dynamically:
function AddBlock(container) {
var $template = $(Template());
$(container).append($template);
$template.find(".AddBlock").click, function () {
AddBlock(CONTAINER);
});
$template.find(".DeleteBlock").click, function () {
DeleteBlock(CONTAINER, GetParentId(this));
});
}

Categories