I have created one form and form after submitting the value I want to show them in a table. In table I have one section where I want to delete or edit a particular user on a button. But when I am passing the id to that function I am getting error saying that refernece error occurred!
function getEmployeeDetails() {
for (var i = 0; i < userArray.length; i++) {
var tr = "<tr>";
tr +=
"<td class='table-data'/td>" +
userArray[i].id +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].name +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].email +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].gender +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].role +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].english +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].hindi +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].othersLang +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].description +
"</td>" +
"<td class='table-data'/td>" +
"<button onclick='deleteUser( userArray[i].id )'>Delete</button> || <button onclick='editUser( userArray[i].id )'>Edit</button>" +
"</td>" +
"</tr>";
tbody.innerHTML += tr;
}
}
function deleteUser(id) {
console.log("delteuser", typeof id, id);
}
function editUser(id) {
console.log("edit", id);
}
Where I have made the mistakes?
The problem is in the string concatenation you are using in the onClick event.
You can use a backtick character instead.
Copy-paste and check the below code.
<html>
<body>
<table id="table"></table>
<script>
getEmployeeDetails();
function getEmployeeDetails() {
let userArray = [{ id: 1 }, { id: 2 }];
var tr = "";
for (var i = 0; i < userArray.length; i++) {
tr +=
`<td class="table-data">
<button onclick="deleteUser(` +
userArray[i].id +
`)">Delete</button> || <button onclick="editUser( ` +
userArray[i].id +
`)">Edit</button>
</td>`;
}
document.getElementById("table").innerHTML = tr;
}
function deleteUser(id) {
console.log("delteuser", typeof id, id);
}
function editUser(id) {
console.log("edit", id);
}
</script>
</body>
</html>
Change
<button onclick='deleteUser( userArray[i].id )'>
To something like
<button onclick='deleteUser('+userArray[i].id+')'>
In your current attempt you are not inserting the value of userArray[i].id but the variable userArray[i].id which is kind of nonsense.
Same story with the editUser function
Related
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
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");
I want to get the value of the input fill from a function to another function but I am not sure how.
From this funtion input fill:
$("#buttonDone4").click(function () {
function productAddToTable() {
$("#table").fadeIn();
// First check if a <tbody> tag exists, add one if not
if ($("#table tbody").length == 0) {
$("#table").after("<tbody></tbody>");
}
// Append product to the table
$("#table").append(
"<tr>" +
"<td>" + document.getElementById("perimeter2").innerHTML + "</td>" +
"<td>" + "4" + "</td>" +
"<td>" + "<input type='text' name='periAns' size='10'/>" + "</td>" +
"</tr>"
);
}
productAddToTable();
$("#buttonDone4").fadeOut();
$(".p1").fadeIn();
$("#buttonCheck").fadeIn();
});
To this function:
$("#buttonCheck").click(function () {
var pa = document.getElementByName["periAns"].value;
var peri = (document.getElementById("perimeter2").innerHTML / 4);
if(peri == pa ){
console.log("yes");
}else{
console.log("no");
}
});
Put ID to the inputs and use jquery.
$("#table").append(
"<tr>" +
"<td>" + document.getElementById("perimeter2").innerHTML + "</td>" +
"<td>" + "4" + "</td>" +
"<td>" + "<input type='text' id ='periAns' size='10'/>" + "</td>" +
"</tr>"
);
}
$("#buttonCheck").click(function () {
var pa = Number($("#periAns").val()) //assuming this is an input
var peri = Number(document.getElementById("perimeter2").innerHTML)
var finPeri = peri / 4
if(finPeri == pa ){
console.log("yes");
}else{
console.log("no");
}
});
having a hard time on addEventlistner. it gives me uncaught reference error when page is loaded
window.onload= initializer;
var refUsers;
var tableBody;
INITIALIZER
function initializer(){
refUsers=firebase.database().ref().child("users");
tableBody = document.getElementById("table_body");
loadTables();
}
LOADS TABLE
function loadTables(){
refUsers.on("value", function(snap){
var data = snap.val();
var file11 = "";
for(var key in data){
file11 += "<tr>" +
"<td>" + data[key].firstname + "</td>" +
"<td>" + data[key].lastname + "</td>" +
"<td>" + data[key].birthdate + "</td>" +
"<td>" + data[key].email + "</td>" +
"<td>" + data[key].date + "</td>" +
"<td>" + data[key].time + "</td>" +
'<td>' +
'<button class="btn btn-sm btnColorAccept center-block okButton" dataOk-confirmation="' + key + '">' +
'<span class="glyphicon glyphicon-ok"></span>' +
'ACCEPT</button>' +
'</td>' +
'<td>' +
'<button class="btn btn-sm btnColorDecline center-block removeButton" dataRemove-confirmation="' + key + '">' +
'<span class="glyphicon glyphicon-remove"></span>' +
'DECLINE</button>' +
'</td>' +
"</tr>;";
}
tableBody.innerHTML = file11;
if(file11 != ""){
var elementForOkButton = document.getElementsByClassName("okButton");
for( var i=0; i< elementForOkButton.length; i++){
elementForOkButton[i].addEventListener("click", okButtonElementFirebase, false);
}
}
});
} //end table function
GOT ERROR ON THIS LINE
elementForOkButton[i].addEventListener("click", okButtonElementFirebase, false);
FOR BUTTON WHEN CLICKED
function okButtonELementFirebase(){
var keyOkButton = this.getAttribute("dataOk-confirmation");
var firebaseRefUsers = refUsers.child(keyOkButton);
firebaseRefUsers.remove();
}
function okButtonELementFirebase(){
You have a typo - okButtonELementFirebase should be okButtonElementFirebase.
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(""));
}
);