splice in javascript change values of my other objects - javascript

NOTE! this is for an extra credit assignment, so I am not looking for code re-write but rather guidance in what I am doing wrong. I have gone through my code several times and I feel like I am just missing something very minor. I have completed it fully with the exception of the following error:
I created an array of objects.
Everything starts off fine. I can create objects and they are added to the array and successfully displayed on my screen with correct values.
The trouble arises when I delete an object from the array. It does delete this object and removes it from my displayed list, but suddenly all the remaining objects get new values. These new values match those of the LAST object I added to the array. I need them to retain their original values!
var tableContent = document.getElementById("tableContent");
var tableString = " ";
var counter = 0;
var courseArray = [];
tableContent.innerHTML = tableString;
function Course(number, title, hours, prereq) {
this.number = number;
this.title = title;
this.hours = hours;
this.prereq = prereq;
}
function createCourse() {
var number = document.getElementById("number-field");
var title = document.getElementById("title-field");
var hours = document.getElementById("hours-field");
var prereq = document.getElementById("prereq-field");
courseArray.push(new Course(number, title, hours, prereq));
buildCourseTableBody();
}
function buildCourseTableBody() {
tableString += "<tr>" +
"<td>" + counter + "</td>" +
"<td>" + courseArray[counter].number.value + "</td>" +
"<td>" + courseArray[counter].title.value + "</td>" +
"<td>" + courseArray[counter].hours.value + "</td>" +
"<td>" + courseArray[counter].prereq.value + "</td>" +
"<td><button id='delete' onClick='deleteCourse(" + counter + ")'><img id=counter src='../image/delete.png' alt='delete course'></button></td>" +
"</tr>";
counter++;
tableContent.innerHTML = tableString;
}
function deleteCourse(counterIndex) {
courseArray.splice(counterIndex, 1);
counter--;
tableString = "";
for (var i = 0; i < courseArray.length; i++) {
tableString += "<tr>" +
"<td>" + i + "</td>" +
"<td>" + courseArray[i].number.value + "</td>" +
"<td>" + courseArray[i].title.value + "</td>" +
"<td>" + courseArray[i].hours.value + "</td>" +
"<td>" + courseArray[i].prereq.value + "</td>" +
"<td><button id='delete' onClick='deleteCourse(" + i + ")'><img id=counter src='../image/delete.png' alt='delete course'></button></td>" +
"</tr>";
}
and HTML code(everything in main, which is wrapped in body. js file is included):
<main id="main-index">
<h1 id="page-caption">CS Department Course Catalog</h1>
<div id="course-list">
<p id="course-list-caption">Course List</p>
<table>
<thead>
<tr>
<th>Count</th>
<th>Number</th>
<th>Title</th>
<th>Hours</th>
<th>Prereq</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tableContent">
</tbody>
</table>
</div>
<div id="course-edit">
<p><input id="number-field" placeholder="Course #, e.g. CS234"></p>
<p><input id="title-field" placeholder="Course title, e.g. Database and Wed Systems Development"></p>
<p><input id="hours-field" placeholder="Credit hours, e.g. 3.0"></p>
<p><input id="prereq-field" placeholder="Course prereqs, e.g. CS150, CS111"></p>
<p><button id="add" onClick="createCourse()">+</button></p>
</div>
</main>

Your error is in createCourse. You are assigning the HTML-Elements instead of their value.
function createCourse() {
var number = document.getElementById("number-field").value;
var title = document.getElementById("title-field").value;
var hours = document.getElementById("hours-field").value;
var prereq = document.getElementById("prereq-field").value;
courseArray.push(new Course(number, title, hours, prereq));
buildCourseTableBody();
}
The class course will hold a reference to the element itself. Like that your functions which generate the table itself, will always get the most current value of the input boxes.
Notice:
Don't forget to adapt buildCourseTableBody and deleteCourse.

Related

Autodesk forge viewer table row click to isolate elements

I am trying to create a dynamic table inside the viewer's page.
each row of the table represents an object from the model and has a couple of different parameters ( name, level, etc..)
I want to make a click event on each row, that isolates the element in the viewer's model.
I have created the table programmatically using js. (the table is created after pressing an external command button )
how can I add an event listener to a row click, that would isolate the element?
this is my code for creating the table after pressing the command button:
var myTable = $('.my-table');
var myArr = rows; //matrix of object values
for (var i = 0; i < myArr.length; i++)
myTable.append("<tr id=" + i + ">" +
" <td>" + myArr[i][0] + "</td>" +
"<td>" + myArr[i][1] + "</td>" +
"<td>" + myArr[i][2] + "</td>" +
"<td>" + myArr[i][3] + "</td>" +
"<td>" + myArr[i][4] + "</td>" +
"<td>" + myArr[i][5] + "</td>" +
"<td>" + myArr[i][6] + "</td>" +
"<td id=" + "tt" + ">" + myArr[i][7] + "</td>" +
"</tr>");
const row = document.getElementById(`${i}`);
row.addEventListener('onClick', function(evt, item) { /// we are using a viewer api property to isolate the
_this.viewer.isolate(_this.modelData.getIds(myArrNames[i][1], item[0]._model.label));
});
First, it's not a Forge issue but a JavaScript syntax and indent issue.
After re-indenting your code, you can see the codes for adding the click event is out of the for-loop, so you need to add the bracket pair to include the codes for adding the click event into the for-loop.
When defining for-loop in JavsScirpt without bracket { and }, it only takes the first line in the count.
In addition, there is no onClick event. When using addEventListener, the event name is click, not onClick.
var myTable = $('.my-table');
var myArr = [[1,2,3,4,5,6,7], [1,2,3,4,5,6,7]]; //matrix of object values
for (var i = 0; i < myArr.length; i++) {
myTable.append("<tr id=" + i + ">" +
" <td>" + myArr[i][0] + "</td>" +
"<td>" + myArr[i][1] + "</td>" +
"<td>" + myArr[i][2] + "</td>" +
"<td>" + myArr[i][3] + "</td>" +
"<td>" + myArr[i][4] + "</td>" +
"<td>" + myArr[i][5] + "</td>" +
"<td>" + myArr[i][6] + "</td>" +
"<td id=" + "tt" + ">" + myArr[i][7] + "</td>" +
"</tr>");
const row = document.getElementById(`${i}`);
row.addEventListener('click', function(evt) { /// we are using a viewer api property to isolate the
_this.viewer.isolate(_this.modelData.getIds(myArrNames[i][1], item[0]._model.label));
});
}
To use onClick, it will become:
const row = document.getElementById(`${i}`);
row.onClick = function(evt) { /// we are using a viewer api property to isolate the
_this.viewer.isolate(_this.modelData.getIds(myArrNames[i][1], item[0]._model.label));
});
Lastly, why not just use jQuery only? The jquey.on can help bind events to dynamically created items, so that the click event will be delegated to any tr element in the table, even if it's added after you bound the event handler.
var myTable = $('.my-table');
var myArr = [[1,2,3,4,5,6,7], [1,2,3,4,5,6,7]]; //matrix of object values
myTable.on('click', 'tr', function() {
_this.viewer.isolate(_this.modelData.getIds(myArrNames[i][1], item[0]._model.label));
});
for (var i = 0; i < myArr.length; i++) {
myTable.append("<tr id=" + i + ">" +
" <td>" + myArr[i][0] + "</td>" +
"<td>" + myArr[i][1] + "</td>" +
"<td>" + myArr[i][2] + "</td>" +
"<td>" + myArr[i][3] + "</td>" +
"<td>" + myArr[i][4] + "</td>" +
"<td>" + myArr[i][5] + "</td>" +
"<td>" + myArr[i][6] + "</td>" +
"<td id=" + "tt" + ">" + myArr[i][7] + "</td>" +
"</tr>");
}
ref: https://stackoverflow.com/a/15420578

How to delete rows other than a random row on a table(Javascript)?

I get data from the user and put it into the table by collating, I want to show a random line from the table I want to delete the other rows
function bilgi(){
var random = Math.floor(Math.random() * (allobjs.length - 1) ) + 1;
if (allobjs[random].id != 'blank'){
allobjs[random].animate({fill: 'rgb(19, 167, 236)'}, 1000);
$(function() {
$.getJSON('/static/yer.json', function(data) {
var deger = $("input[name=deger]").val()
var al = deger.split(",")
$.each(data, function(i, f) {
if(f.plaka == random){
var tblRow = "<tr>" +
"<td>" + "<img class='aaa'src='/static/bayrak.jpg' alt='' />" + "</td>" +
"<td>" + deger + "</td>" +
"<td>" + f.yerler + "</td>" +
"<td>" + f.bolge + "</td>" +
"<td>" + f.ili + "</td>" +
"<td>" + f.teskilati + "</td>" +
"<td>" + f.acm + "</td>" +
"</tr>"
$("tbody").append(tblRow);
}
});
$("tbody tr").hide()
var toplam= $("tbody tr").size()
ratgel=Math.floor(Math.random() * toplam);
$("tbody tr").eq(ratgel).show(1000)
});
});
}}
In javascript add class NOSHOW to each tr you want to hide Then using css .NOSHOW{display:none;} If you want a complete solution show your html.
something like the following might work:
At the start of your function add the following:
var tr = getElementsByTagName('tr');
for(var i = 0; i < tr.length;i++){
tr[i].className += "noshow";
}
then in you html add:
<style>
.noshow{
display:none;
}
</style>
This should work as you then append the row you want to the end of the table.
Later, when you want to display the entire table again you can use:
element.classList.remove("noshow");

Javascript Append Function, Need to build a loop

I have a .php file where I am using both HTML and JavaScript to display items from my database. I have a JavaScript append function that is creating cards where each item is display. On my cards, I have a button that will expand the card to show product history. Some products have more history than others so the expansion needs to be dynamic. The historical data is being pulled from database and is initially in a php array. I originally was going to institute php into the javascript append function but I could not figure out how to set the JavaScript index variable 'I' to my php index. So I want to just stay with JavaScript. But I don't know how to write a loop in the middle of this append function that will loop through the historical array and populate the expansion. Below is what I am attempting. I took out a lot of the lines in the append function but you can see what I am trying to do.
function get_products() {
clear_cards();
$.each(productNumbers,
function(i, value) {
$('.main_card_shell').append(
"<div class='card_content card_style' id='card" + i + "'>" +
"<div id='card_tab2" + i + "' class='tabcontent' data-tab='tab-name2'>" +
"<div class='details_tables'>" +
"<table>" +
"<tr>" +
"<th>Item Type</th>" +
"<th>Painted</th>" +
"<th>Last Sold" +
"<a id='_close_tab" + i + "' class='tablinks tab_override' onclick=\"openCity(event,'card_tab4" + i + "')\">" +
"<i class='large angle up icon'></i>" +
"</a>" +
"</th>" +
"</tr>" +
"<tr>" +
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength)
{
+ "<td>" + itemtypesplit[counter] + "</td>" +
+ "<td>" + itemdatesplit[counter] + "</td>" +
counter = counter + 1;
}
+
"</tr>" +
"</table>" +
"</div>" +
"</div>" +
Please help. I had it working with PHP inserted in, but I just couldn't figure out how to set it to a PHP variable.
Place this code into a function:
function getSomething(i) {
var html = '';
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength) {
html += "<td>" + itemtypesplit[counter] + "</td>";
html += "<td>" + itemdatesplit[counter] + "</td>";
counter = counter + 1;
}
return html;
}
And then use it in your HTML building block:
'<some html>' + getSomething(i) + '<some other html>'

$.post to display table with for in

i'm trying to display a table with jsonObject response, using loop for, to begin with objetosRetorna.Propiedad_Msg is always not null, so rows in table don't show anything just columns showing a error message
i'm not using AJAX.
Here is my code.
....
$.post("ListaUser.php",
{
IdPost: DatosJson },
function(objetosRetorna){
for (var i in objetosRetorna){
if(objetosRetorna.Propiedad_Msg=='Null'){
$("#tabla tbody").html("");
var nuevaFila=
"<tr>"
+"<td><a href='NewUser.php?a=" + objetosRetorna.Prop_id + "'><button type='button' class='btn btn-default light-green lighten-1'>Editar </button></a> <button type='button' onclick='Eliminar("+objetosRetorna.Prop_id+")' class='red lighten-1 btn btn-danger '>Eliminar</button></td>"
+"<td>"+objetosRetorna[i].Prop_titulo+"</td>"
+"<td>"+objetosRetorna[i].Prop_propiedad+"</td>"
+"<td>"+objetosRetorna[i].Prop_categoria+"</td>"
+"<td>"+objetosRetorna[i].Prop_direccion+"</td>"
+"<td>"+objetosRetorna[i].Prop_colonia+"</td>"
+"<td>"+objetosRetorna[i].Prop_coordenadas+"</td>"
+"<td>"+objetosRetorna[i].Prop_superficie+"</td>"
+"<td>"+objetosRetorna[i].Prop_recamaras+"</td>"
+"<td>"+objetosRetorna[i].Prop_imagenes+"</td>"
+"<td>"+objetosRetorna[i].Prop_precio+"</td>"
+"<td>"+objetosRetorna[i].Prop_antiguedad+"</td>"
+"<td>"+objetosRetorna[i].Prop_fecha+"</td>"
+"<td>"+objetosRetorna[i].Prop_descripcion+"</td>"
+"<td>"+objetosRetorna[i].Prop_prop_id+"</td>"
+"</tr>";
$(nuevaFila).appendTo("#tabla tbody");
}
if (objetosRetorna.Propiedad_Msg!="Null") {
var nuevaFila =
"<tr>"
+"<td colspan='5'><center><font color='red'>"+objetosRetorna.Propiedad_Msg+"</font></center></td>"
+"</tr>";
$(nuevaFila).appendTo("#tabla tbody");
}
}
},"json");
Json Response
[{"Prop_id":"32",
"Prop_titulo":"Mi titulo de propiedad",
"Prop_propiedad":"Casa",
"Prop_categoria":"Renta",
"Prop_direccion":"Calle Term",
"Prop_colonia":"Progreso",
"Prop_coordenadas":"499965",
"Prop_superficie":"40m2",
"Prop_recamaras":"5",
"Prop_imagenes":"imagenes",
"Prop_precio":"4500","Prop_antiguedad":"15 a\u00f1os","Prop_fecha":"0000-00-00",
"Prop_descripcion":"Departamen","Prop_prop_id":"10",
"Propiedad_Msg":"Null"}....]
Thank you.
Hope somebody can help me
UPDATE.... TypeError: objetosRetorna.map is not a function[Saber más]index.php:62:30
function(objetosRetorna) {
var rows = objetosRetorna.map (function(objeto){
if (objeto.Propiedad_Msg == 'Null') {
return "<tr>" +
"<td><a href='NewUser.php?a=" + objeto.Prop_id + "'><button type='button' class='btn btn-default light-green lighten-1'>Editar </button></a> <button type='button' onclick='Eliminar("+objeto.Prop_id+")' class='red lighten-1 btn btn-danger '>Eliminar</button></td>"+
"<td>"+objeto.Prop_titulo+"</td>"+
"<td>"+objeto.Prop_propiedad+"</td>"+
"<td>"+objeto.Prop_categoria+"</td>"+
"<td>"+objeto.Prop_direccion+"</td>"+
"<td>"+objeto.Prop_colonia+"</td>"+
"<td>"+objeto.Prop_coordenadas+"</td>"+
"<td>"+objeto.Prop_superficie+"</td>"+
"<td>"+objeto.Prop_recamaras+"</td>"+
"<td>"+objeto.Prop_imagenes+"</td>"+
"<td>"+objeto.Prop_precio+"</td>"+
"<td>"+objeto.Prop_antiguedad+"</td>"+
"<td>"+objeto.Prop_fecha+"</td>"+
"<td>"+objeto.Prop_descripcion+"</td>"+
"<td>"+objeto.Prop_prop_id+"</td>"+
"</tr>";
}
return "<tr>" +
"<td colspan='5'><center><font color='red'>"+objeto.Propiedad_Msg+"</font></center></td>"+
"</tr>";
});
$("#tabla tbody").html(rows.join(""));
}
);
Objects, {}, in JavaScript does not have the method .map(), it's only for Arrays, [].
So in order for your code to work change data.map() to data.props.map()
And json response to something like
{"props":[
{"Prop_id":"32"},
{"Prop_titulo":"Mi titulo de propiedad"},
{"Prop_propiedad":"Casa"},
{"Prop_categoria":"Renta"},
{"Prop_direccion":"Calle Term"},
...]}
Something to read .map() on:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
PS. if you just want to iterate json and you can make your props into array you can iterate objects like this:
for (var key in objetosRetorna) {
if (objetosRetorna.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
If you need more in-depth fix or explanation please leave a comment.
You need to refer to the entry you're looping over. Instead of
for (var i in objetosRetorna){
if(objetosRetorna.Propiedad_Msg=='Null'){
you would want
for (var i in objetosRetorna){
if(objetosRetorna[i].Propiedad_Msg=='Null'){
// --------------^^^
You make the same small mistake later with objetosRetorna.Prop_id a couple of times.
But, for-in isn't the correct way to loop through an array. You have lots of options, but here I'd probably use forEach.
Also, unrelated, but you have
if (objetosRetorna.Propiedad_Msg == 'Null') {
and then immediately after that
if (objetosRetorna.Propiedad_Msg != 'Null') {
In that situation, you can just use else to avoid the maintenance issue of having the condition repeated.
You're also removing everything from the table when adding each row, which means you'll end up with just the last row. So instead of forEach, let's use map to return an array of row strings:
So taking all that together (see *** comments):
$.post("ListaUser.php", {
IdPost: DatosJson
},
function(objetosRetorna) {
// *** Note use of `map` to get a string for each row
var rows = objetosRetorna.map(function(objecto) { // *** We receive each entry as the `objecto` argument
// Use `objeto` for the various things below
if (objeto.Propiedad_Msg == 'Null') {
return "<tr>" +
"<td><a href='NewUser.php?a=" + objeto.Prop_id + "'><button type='button' class='btn btn-default light-green lighten-1'>Editar </button></a> <button type='button' onclick='Eliminar(" + objeto.Prop_id + ")' class='red lighten-1 btn btn-danger '>Eliminar</button></td>" +
"<td>" + objetos.Prop_titulo + "</td>" +
"<td>" + objetos.Prop_propiedad + "</td>" +
"<td>" + objetos.Prop_categoria + "</td>" +
"<td>" + objetos.Prop_direccion + "</td>" +
"<td>" + objetos.Prop_colonia + "</td>" +
"<td>" + objetos.Prop_coordenadas + "</td>" +
"<td>" + objetos.Prop_superficie + "</td>" +
"<td>" + objetos.Prop_recamaras + "</td>" +
"<td>" + objetos.Prop_imagenes + "</td>" +
"<td>" + objetos.Prop_precio + "</td>" +
"<td>" + objetos.Prop_antiguedad + "</td>" +
"<td>" + objetos.Prop_fecha + "</td>" +
"<td>" + objetos.Prop_descripcion + "</td>" +
"<td>" + objetos.Prop_prop_id + "</td>" +
"</tr>";
}
// It's not null
return "<tr>" +
"<td colspan='5'><center><font color='red'>" + objeto.Propiedad_Msg + "</font></center></td>" +
"</tr>";
});
// *** Now we replace the table contents with the strings (joined into one string)
$("#tabla tbody").html(rows.join(""));
}
);

How can I dynamically output each index in an array to HTML

I'm attempting to create a tooltip that prints every indexed position of a particular array dynamically.
I first start with a 'for' loop that pushes the targeted values that I want displayed in the tooltip to an array if they pass a condition like so:
var myArray = [];
for (var i = 0; i < ccirdata.length; i++) {
if (myArray[i].catType === 'I') {
myArray.push(ccirdata[i].catNum);
}
}
I'd like to iterate/print EACH index item of the array:
scope.data = [
{
key: 'Category I',
MyAttribute:<INSERT HERE>
},
So that my tooltip is formatted as such where 'MyAttribute' will create a new row, "< tr >" for every index item:
var header =
"<thead>" +
"<tr>" +
"<td class='legend-color-guide'><div style='background-color: " + series.color + ";'></div></td>" +
"<td class='key'>" + series.key + " CCIRs:</td>" +
"</tr>" +
"</thead>";
var rows =
"<tr>" +
"<td class='key'><strong>" + series.key + "</strong></td>" +
"<td class='x-value'>" + MyAttribute + "</td>" +
"</tr>"
return "<table>" +
header +
"<tbody>" +
rows +
"</tbody>" +
"</table>";
I'm just not sure how this can be done, since iterations require javascript, and i'm looking to print each item in html format (the tooltip)

Categories