JQuery adding and saving data input in row - javascript

I am having trouble saving the new row. When i click on add person I am able to input the data, however, i am not sure how to save it and add a new row.
I know i have to make a function for the save button to work however i am stuck on how to make it work. I have tried a few times but to no avail.
var isNewLineToggled = false;
var isAscending = {
name : false,
lastName: false,
dob: false
};
$(".main").append("<input placeholder='search by name' class='search'/><br/><br/>")
$(".main").append("<button onclick=addPerson()>add a person</button><br/><br/>")
var table = $(".main").append("<table></table>");
var thead = '<thead><tr></tr></thead>';
table.append(thead);
var header = [
{ title: 'Name', sortBy: 'name'},
{ title: 'Last Name', sortBy: 'lastName'},
{ title: 'Date of birth', sortBy: 'dob'}
].map(
function(header) {
var sortButton = '<button id="' + header.sortBy + '" onclick=sortRows("'+ header.sortBy + '")>/\\</button>';
$('thead').append('<th>' + header.title + ' ' + sortButton + '</th>');
}
)
var tbody = "<tbody></tbody>";
var data = [ {name: 'Peter', lastName: 'Petterson', dob: '13/12/1988'},
{name: 'Anna', lastName: 'Jones', dob: '06/02/1968'},
{name: 'John', lastName: 'Milton', dob: '01/06/2000'},
{name: 'James', lastName: 'White', dob: '30/11/1970'},
{name: 'Luke', lastName: 'Brown', dob: '15/08/1999'}
];
$('.search').change(function(event) {
searchedName = event.target.value;
})
table.append(tbody);
data.map(
function(row, i) {
$('tbody').append(
'<tr><td>' + row.name +
'</td><td>' + row.lastName +
'</td><td>' + row.dob +
'</td><td><button onclick=editRow('+i+')>edit</button><button>delete</button></td></tr>'
)
}
)
var editableRow = "<td><input/></td><td><input/></td><td><input type='date'/></td><td><button onclick=saveRow()>save</button></td>";
var addPerson = function() {
isNewLineToggled = !isNewLineToggled;
if (isNewLineToggled) {
$('tbody').prepend('<tr>' + editableRow + '</tr>')
} else {
$('tbody > tr:first-child').remove();
}
}
var editRow = function(rowNumber) {
var name = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:first-child').text();
var lastName = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(2)').text();
var dob = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(3)').text();
$('tbody > tr:nth-child('+(rowNumber + 1)+')').html(editableRow2);
$('tbody > tr:nth-child('+(rowNumber + 1)+') > td:first-child > input').val(name);
$('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(2) > input').val(lastName);
}

You can add row like this, two small changes:
$(".main").append("<button class='add'>add a person</button><br/><br/>")
Remove inline event handler, no need for it. And your function could be:
$('body').on('click','.add', function() { //you will need event delegation, because of dynamically added elements
isNewLineToggled = !isNewLineToggled;
if (isNewLineToggled) {
$('tbody').prepend('<tr>' + editableRow + '</tr>')
} else {
$('tbody > tr:first-child').remove();
}
});
Since your editableRow variable isn't defined, i've used just one cell with text for demo:
https://jsfiddle.net/2c97auey/1/
P.S. Your editableRow should have input(s) values, properly placed in cells. Shouldn't be too hard.

Related

JSON result value as key in JavaScript/jQuery

I have a JSON result where I want to create an accordion menu, I want one value of similar results as title of those similar rows, please check below to see what I did.
Suppose a I have below JSON object
var items = [
{label: "TY2021H", name: "10-Yr T-Notes", value: "TY2021H"},
{label: "TY2020Z-TY2021H", name: "10-Yr T-Notes Spread", value: "TY2020Z-TY2021H"},
{label: "TY2021H-TY2021M", name: "10-Yr T-Notes Spread", value: "TY2021H-TY2021M"},
{label: "TY2020Z-2*TY2021H+TY2021M", name: "10-Yr T-Notes Butterfly", value: "TY2020Z-2*TY2021H+TY2021M"}]
The related part of my JS code is as follow:
var myUL = $("#accordion");
myUL.empty();
var currentName = "";
for (var i = 0; i <= items.length - 1; i++) {
var label = items[i].label;
if (items[i].name != currentName) {
currentName = items[i].name;
list +=
'<a href="#demo' +
i +
'" class="list-group-item list-group-item-info" data-toggle="collapse" data-parent="#accordion">' +
currentName +
' <span id="opnClsSign" class="glyphicon glyphicon-menu-down"></span></a>';
list += '<div class="collapse in" id="demo' + i + '">';
}
list += '' + label + "";
}
list += "</div>";
myUL.append(list);
Part of my HTML div
<div class="list-group panel" id="accordion"></div>
Result I get now
What I expect
Code indentation can help in a situation like this. Your last two lines should be inside the loop for the code to make sense. In every iteration, you must close the div and add the code to myUL:
var items = [
{label: "TY2021H", name: "10-Yr T-Notes", value: "TY2021H"},
{label: "TY2020Z-TY2021H", name: "10-Yr T-Notes Spread", value: "TY2020Z-TY2021H"},
{label: "TY2021H-TY2021M", name: "10-Yr T-Notes Spread", value: "TY2021H-TY2021M"},
{label: "TY2020Z-2*TY2021H+TY2021M", name: "10-Yr T-Notes Butterfly", value: "TY2020Z-2*TY2021H+TY2021M"}]
var myUL = $("#accordion");
myUL.empty();
var currentName = "";
for (var i = 0; i <= items.length - 1; i++) {
var label = items[i].label;
var list = '';
if (items[i].name != currentName) {
currentName = items[i].name;
list +=
'<a href="#demo' +
i +
'" class="list-group-item list-group-item-info" data-toggle="collapse" data-parent="#accordion">' +
currentName +
' <span id="opnClsSign" class="glyphicon glyphicon-menu-down"></span></a>';
list += '<div class="collapse in" id="demo' + i + '">';
}
list += '' + label + "";
list += "</div>";
myUL.append(list);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-group panel" id="accordion"></div>
Also, you needed to define list.
I resolved the issue my self, and I have added the final source code into this pen:
[https://codepen.io/rafihaidari/pen/ExyBGVK]

Button after div that contains dynamic elements without touch HTML

i need an help.
I have this code and i have to put a Save button to the end for store the changes or the new entry in DB.
I have the problem that i haven't idea to how put button in the end without change HTML code because i can't, i wuold insert button via javascript,
how can i do?
p.s: The problem is that i can't insert in those function because the function under here is called everytime a press a button, if a press another time is called another, and again.
p.s2: Tell me if the code is ok, in other case tell me how can i improve this
Thank you
$().ready(function() {
//Creation of array to simulate data from DB
var obj1 =
{
id: "1",
name: "Bryan",
surname: "Del Bianco"
};
var obj2 =
{
id: "2",
name: "Luca",
surname: "Del Bianco"
};
var exampleOfDatabase = new Array();
exampleOfDatabase.push(obj1);
exampleOfDatabase.push(obj2)
visualizzaModifica(exampleOfDatabase, $("#divTeamLeaderProduzione"))
function visualizzaModifica(array, div)
{
div.html("");
div.append("<br>");
let i = 1;
array.forEach(function(e) {
div.append(
"<div id='div" + i + "' class='input-group'>" +
"<input type='text' id='inputModificaNome" + i + "' class='form-control' value='" + e.name + "'>" +
"<input type='text' id='inputModificaCellulare" + i + "' class='form-control' value='" + e.surname + "'>" +
"</div>"
);
i++;
});
aggiungiInput(i, div);
}
function aggiungiInput(i,div)
{
if($("#div"+i).length == 0)
{
var next = $("<div>",
{
id: 'div'+i,
class: 'input-group'
});
var inputNome = $('<input>',
{
id: 'inputModificaNome'+i,
type: 'text',
class: 'form-control'
});
var inputCellulare = $('<input>',
{
id: "inputModificaCellulare"+i,
type: 'text',
class: 'form-control'
});
next.on('change', function ()
{
aggiungiInput(i+1, div);
});
next.append(inputNome);
next.append(inputCellulare);
div.append(next);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divTeamLeaderProduzione">
</div>
$().ready(function() {
//Creation of array to simulate data from DB
var obj1 =
{
id: "1",
name: "Bryan",
surname: "Del Bianco"
};
var obj2 =
{
id: "2",
name: "Luca",
surname: "Del Bianco"
};
var exampleOfDatabase = new Array();
exampleOfDatabase.push(obj1);
exampleOfDatabase.push(obj2)
visualizzaModifica(exampleOfDatabase, $("#divTeamLeaderProduzione"))
function visualizzaModifica(array, div)
{
div.html("");
div.append("<br>");
let i = 1;
array.forEach(function(e) {
div.append(
"<div id='div" + i + "' class='input-group'>" +
"<input type='text' id='inputModificaNome" + i + "' class='form-control' value='" + e.name + "'>" +
"<input type='text' id='inputModificaCellulare" + i + "' class='form-control' value='" + e.surname + "'>" +
"</div>"
);
i++;
});
aggiungiInput(i, div);
}
function aggiungiInput(i,div)
{
if($("#div"+i).length == 0)
{
var next = $("<div>",
{
id: 'div'+i,
class: 'input-group'
});
var inputNome = $('<input>',
{
id: 'inputModificaNome'+i,
type: 'text',
class: 'form-control'
});
var inputCellulare = $('<input>',
{
id: "inputModificaCellulare"+i,
type: 'text',
class: 'form-control'
});
next.on('change', function ()
{
aggiungiInput(i+1, div);
});
next.append(inputNome);
next.append(inputCellulare);
div.append(next);
}
$("#btnSave").remove();
div.append("<input type='button' value='Save' id='btnSave' />");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divTeamLeaderProduzione">
</div>
I removed the button and placed it when needed. Hope it helps. Cheers..!!

Making table and it's content via JavaScript

Hw to download arr content into the table cells from left to right and from up to down? What is wrong with my code? How to solve the problem? Thanks in advance.
<button onclick="myFunction()></button>
<table id="myTable" border='1px'>
<tr>
<th>N</th>
<th>Name</th>
<th>Surname</th>
<th>tel.</th>
<th>email</th>
</tr>
</table>
var arr=[[1,2,3,4,'a'],[5,6,7,8,'b'],[9,10,11,12,'c']];
function myFunction() {
createTable();
}
function createTable(){
var i,j;
var table = document.getElementById("myTable");
for( i=0; i<arr.length; i++ ) {
var row = table.insertRow(1);
for( j=0,k=0; j<5, k<arr[i].length;j++, k++ ) {
var cell = row.insertCell(0);
cell.innerHTML = arr[i][k];
}
}
}
Well i am not sure about your data structure but if you get your data in the following form.
[ { N: 1, Name: 2, Surname: 3, Tel: 4, email: 'a' },
{ N: 5, Name: 6, Surname: 7, Tel: 8, email: 'b' },
{ N: 9, Name: 10, Surname: 11, Tel: 12, email: 'c' } ]
You can use the following tableMaker function. It will take the properties as headers (if second argument is provided as true) and values as corresponding cells to generate an HTML text. So here it goes as follows;
var tableMaker = (o,h) => {var keys = o.length && Object.keys(o[0]),
rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "</" + t + "></tr>"
: "<" + t + ">" + c + "</" + t + ">"),"<tr>"),
rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),h ? rowMaker(keys,"th") : []);
return rows.length ? "<table>" + rows + "</table>" : "";
},
arr = [[1,2,3,4,'a'],[5,6,7,8,'b'],[9,10,11,12,'c']],
tableObj = arr.map(e => ({N: e[0], Name: e[1], Surname : e[2], Tel: e[3], email: e[4]})),
tableHTML = tableMaker(tableObj,true);
document.write(tableHTML);

Cannot set property 'innerHTML' of null in javascript

guys i have a column which contains text and button and what i want is when click on the button the text changed .. here is my code
var count = 0;
$(document).ready(function() {
$("#jqGrid").jqGrid({
data: data.rows,
datatype: "local",
styleUI: "Bootstrap",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 180,
editable: true,
edittype: "custom",
id: "CustomerID",
editoptions: {
custom_element: function(value, options) {
var parts = value.split(' ');
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText();"/></div>';
count++;
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
return first;
}
}
},
],
});
});
function setText() {
document.getElementById("txt_" + count).innerHTML = "hey";
}
so why it gives me that exception ? .. plz help .. btw i am beginner
the count inside setText is undefined.
1st change onclick function of button to pass the count variable
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText(' + count + ');"/></div>';
then accept the count as parameter
function setText(count) {
document.getElementById("txt_" + count).innerHTML = "hey";
}
You can pass count to the function:
var count = 0;
$(document).ready(function() {
$("#jqGrid").jqGrid({
data: data.rows,
datatype: "local",
styleUI: "Bootstrap",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 180,
editable: true,
edittype: "custom",
id: "CustomerID",
editoptions: {
custom_element: function(value, options) {
var parts = value.split(' ');
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText(' + count + ');"/></div>';
count++;
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
return first;
}
}
},
],
});
});
function setText(count) {
document.getElementById("txt_" + count).innerHTML = "hey";
}

Comparing Objects in Array

Ok so Im building a product sorting watch and this is what I have so far.
jQuery(document).ready(function() {
// starter jQuery file
/* Watches Array */
var watchesArray = [
{
model: "Swim",
image:"",
price: 149.99,
sports:["Swimming"],
touchScreen:false,
GPS:false,
heartRateMonitor:false,
hrZoneTraining:false,
caloriesBurned:true,
distance:true,
pace:true,
multisport:false,
swimMetrics:true,
memory:"Up to 30 workouts",
virtualPartner:false,
virtualRacer:false,
paceAlert:false,
timeDistanceAlert:false,
hydrationAlert:false,
rechargeableBattery:false,
waterResistant:"Up to 50 meters",
syncWithComputer:true,
other:"",
},
{
model: "FR 10",
image:"fr_10.jpg",
price: 129.99,
sports:["Running"],
touchScreen:false,
GPS:true,
heartRateMonitor:false,
hrZoneTraining:false,
caloriesBurned:false,
distance:true,
pace:true,
multisport:false,
swimMetrics:false,
memory:"Up to 7 workouts",
virtualPartner:false,
virtualRacer:false,
paceAlert:false,
timeDistanceAlert:false,
hydrationAlert:false,
rechargeableBattery:true,
waterResistant:"Up to 50 meters",
syncWithComputer:false,
other:"-Virtual Pacer(compares running pace to target)</br>-Walk/Run feature",
checkBox:"<input type='checkbox' name='he' value='jk' id='compare'>"
},
{
model: "FR 15",
image:"fr_15.jpg",
price: 199.99,
sports:["Running"],
touchScreen:false,
GPS:true,
heartRateMonitor:true,
hrZoneTraining:true,
caloriesBurned:true,
distance:true,
pace:true,
multisport:false,
swimMetrics:false,
memory:"Up to 7 workouts",
virtualPartner:false,
virtualRacer:false,
paceAlert:false,
timeDistanceAlert:false,
hydrationAlert:false,
rechargeableBattery:true,
waterResistant:"Up to 50 meters",
syncWithComputer:false,
other:"-Virtual Pacer (compares running pace to target) </br>Walk/Run feature</br>-Activity",
},
{
model: "FR 220",
image:"fr_220.jpg",
price: 299.99,
sports:["Running"],
touchScreen:false,
GPS:true,
heartRateMonitor:true,
hrZoneTraining:true,
caloriesBurned:true,
distance:true,
pace:true,
multisport:false,
swimMetrics:false,
memory:"200 hours of data",
virtualPartner:false,
virtualRacer:false,
paceAlert:true,
timeDistanceAlert:false,
hydrationAlert:true,
rechargeableBattery:true,
waterResistant:"Up to 50 meters",
syncWithComputer:true,
other:"-Walk/Run feature</br>-Interval Training",
},
{
model: "FR 620",
image:"fr_620.jpg",
price: 449.99,
sports:["Running"],
touchScreen:true,
GPS:true,
heartRateMonitor:true,
hrZoneTraining:true,
caloriesBurned:true,
distance:true,
pace:true,
multisport:false,
swimMetrics:false,
memory:"200 hours of data",
virtualPartner:true,
virtualRacer:false,
paceAlert:true,
timeDistanceAlert:true,
hydrationAlert:true,
rechargeableBattery:true,
waterResistant:"Up to 50 meters",
syncWithComputer:true,
other:"-VO2 Max</div></br>-Walk/Run feature</br>-Interval Training",
},
{
model: "FR 310 XT",
image:"",
price: 349.99,
sports:["Multisport"],
touchScreen:false,
GPS:true,
heartRateMonitor:true,
hrZoneTraining:true,
caloriesBurned:true,
distance:true,
pace:true,
multisport:true,
swimMetrics:false,
memory:"1000 laps",
virtualPartner:true,
virtualRacer:true,
paceAlert:true,
timeDistanceAlert:true,
hydrationAlert:true,
rechargeableBattery:true,
waterResistant:"Up to 50 meters",
syncWithComputer:true,
other:"-Interval Training",
},
{
model: "FR70",
image:"",
price: 149.99,
sports:["Fitness"],
touchScreen:false,
GPS:false,
heartRateMonitor:true,
hrZoneTraining:true,
caloriesBurned:true,
distance:true,
pace:true,
multisport:false,
swimMetrics:false,
memory:"Up to 20 hrs of data",
virtualPartner:true,
virtualRacer:false,
paceAlert:true,
timeDistanceAlert:true,
hydrationAlert:false,
rechargeableBattery:false,
waterResistant:"Up to 50 meters",
syncWithComputer:true,
other:"-Interval Training",
},
];
/* End Watch Array */
/* different sports arrays filtered */
var runningArray = watchesArray.filter(function(watch) {
return watch.sports.indexOf('Running') !== -1;
});
var swimmingArray = watchesArray.filter(function(watch) {
return watch.sports.indexOf('Swimming') !== -1;
});
var multisportArray = watchesArray.filter(function(watch) {
return watch.sports.indexOf('Multisport') !== -1;
});
var fitnessArray = watchesArray.filter(function(watch) {
return watch.sports.indexOf('Fitness') !== -1;
});
function compare() {
if ($('#page-2 div:nth-of-type(1)').hasClass('running-category')) {
var sportArray = runningArray;
}
if ($('#page-2 div:nth-of-type(2)').hasClass('swimming-category')) {
var sportArray = swimmingArray;
}
if ($('#page-2 div:nth-of-type(3)').hasClass('multisport-category')) {
var sportArray = multisportArray;
}
if ($('#page-2 div:nth-of-type(4)').hasClass('fitness-category')) {
var sportArray = fitnessArray;
}
var sportArrayLength = $(sportArray).length;
for (var i = 0; i < sportArrayLength; i++) {
var watchModel = "<div class='watch-model'>"+sportArray[i].model+"</div>",
watchImage = "<div class='watch-image'>"+sportArray[i].image+"</div>",
watchPrice = "<div class='watch-price'>$"+sportArray[i].price+"</div>",
watchSports = "<div class='watch-sports'>"+sportArray[i].sports+"</div>",
watchTouch = "<div class='watch-touch'>"+sportArray[i].touchScreen+"</div>",
watchGPS = "<div class='watch-gps'>"+sportArray[i].GPS+"</div>",
watchHeart = "<div class='watch-heart'>"+sportArray[i].heartRateMonitor+"</div>",
watchHRZone = "<div class='watch-zone'>"+sportArray[i].hrZoneTraining+"</div>",
watchCalories = "<div class='watch-calories'>"+sportArray[i].caloriesBurned+"</div>",
watchDistance = "<div class='watch-distance'>"+sportArray[i].distance+"</div>",
watchPace = "<div class='watch-pace'>"+sportArray[i].pace+"</div>",
watchMultiSport = "<div class='watch-swim-metrics'>"+sportArray[i].multisport+"</div>",
watchSwimMetrics = "<div class='watch-multi'>"+sportArray[i].multisport+"</div>",
watchMemory = "<div class='watch-memory'>"+sportArray[i].memory+"</div>",
watchVirtualPartner = "<div class='watch-virtual-partner'>"+sportArray[i].virtualPartner+"</div>",
watchVirtualRacer = "<div class='watch-virtual-racer'>"+sportArray[i].virtualRacer+"</div>",
watchPaceAlert = "<div class='watch-pace-alert'>"+sportArray[i].paceAlert+"</div>",
watchTimeDistanceAlert = "<div class='watch-time-distance-alert'>"+sportArray[i].timeDistanceAlert+"</div>",
watchHydrationAlert = "<div class='watch-hydration'>"+sportArray[i].hydrationAlert+"</div>",
watchRechargeable = "<div class='watch-rechargeable'>"+sportArray[i].rechargeableBattery+"</div>",
watchWaterResistance = "<div class='watch-water-resistance'>"+sportArray[i].waterResistant+"</div>",
watchSync = "<div class='watch-syncs'>"+sportArray[i].syncWithComputer+"</div>",
watchOther = "<div class='watch-other'>"+sportArray[i].other+"</div>",
watchesTotal ="<div class='item-container'>"+ watchModel + watchImage + watchPrice + watchSports + watchTouch + watchGPS + watchHeart + watchHRZone + watchCalories + watchDistance + watchPace + watchMultiSport + watchSwimMetrics + watchMemory + watchVirtualPartner + watchVirtualRacer + watchPaceAlert + watchTimeDistanceAlert + watchHydrationAlert + watchRechargeable + watchWaterResistance + watchSync + watchOther+"</div>"
;
$('.comparison-container').append(watchesTotal);
// alert(watchModel)
}
} //end function
$("#page-4 .continue-button").click(function() {
$('.comparison-container').empty();
compare();
});
//var inArray = $.inArray(true, watchesArray[0].multisport)
// alert(inArray)
}); // ready method
So the flow is basically click a sport, filter through the array and make new array with only those items that have that sport, then select a som features that you which to have and when click continue those items that meet the criteria are displayed.
For the last part which is where I am stuck is that when those watches are displayed I have to be able to select a checkbox of those products that interest me so I can then continue and have those selected watches display with all of their details. So basically I need to figure out how to compare two objects from an array by selecting the ones that I want from the page.
On Page 3 you basically have a list of the array items and a compare checkbox under each one.I just need to be able to pass on those products that were selected to the next page
how to compare two objects from an array
Use JSON.stringify to compare the literals:
var foo = [{"1":2},{"1":3},{"2":3},{"1":2}];
var bar = JSON.stringify(foo[0]) === JSON.stringify(foo[1]);
var baz = JSON.stringify(foo[0]) === JSON.stringify(foo[3]);
Use an array as the second param to guarantee ordering of the key enumeration:
(JSON.stringify({a: 1, b: 2}, ["a","b"]) === JSON.stringify({b: 2, a: 1}, ["a","b"]))

Categories

Resources