Delete Firebase entries onclick in a button from a insertAdjacentHTML - javascript

I am trying to delete some entries in FirebaseDatabase and I am having problems. The console returns the error Uncaught SyntaxError: Invalid or unexpected token only in the first entry, and for the others returns Uncaught ReferenceError: MXcLdklS39mrnk7PQEe is not defined at HTMLButtonElement.onclick.
The code is the following:
const database = firebase.database();
var imagenBanner, count;
div = document.getElementById( 'accordion' );
database.ref(`/marketing/banners`).once('value').then(function (snap) {
count = 1;
snap.forEach(function (childSnapshot) {
console.log(childSnapshot.val().titulo)
var str =`
<div class="card">
<div class="card-header" id="heading${count}">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapse${count}" aria-expanded="true" aria-controls="collapse${count}">
${childSnapshot.val().titulo}
</button>
</h5>
</div>
<div id="collapse${count}" class="collapse show" aria-labelledby="heading${count}" data-parent="#accordion">
<div class="card-body">
Introduce el banner que se mostrara al iniciar la aplicación. Especifique las imágenes y la descripción de la página.
<div style="margin: 20px 50px;">
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Titulo</span>
<input id="bannerTit${childSnapshot.key}" type="text" class="form-control" placeholder="Titulo" aria-label="Titulo" aria-describedby="Titulo" value="${childSnapshot.val().titulo}">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Descripción</span>
<input id="bannerDes${childSnapshot.key}" type="text" class="form-control" placeholder="Descripción" aria-label="Descripción" aria-describedby="Descripción" value="${childSnapshot.val().descripcion}">
</div>
<div style="width:auto; margin:0 auto; text-align: center;">
<img src="${childSnapshot.val().imagen}" class="d-inline-block align-middle d-lg-none" style="max-width:100%; align-self: center; display: inline-block!important;" alt="">
</div>
<div class="custom-file" style="margin: auto; text-align: center;">
<input type="file" class="form-control" id="inputImage${childSnapshot.key}" accept="image/*">
</div>
<p style="margin: 15px 0px; text-align: end;">
<button class="btn btn-dark" id="guardarButton${childSnapshot.key}" class="btn btn-sm btn-outline-secondary" onclick="saveBanner(${childSnapshot.key})">Guardar Banner</button>
<button class="btn btn-danger" id="eliminarButton${childSnapshot.key}" class="btn btn-sm btn-outline-secondary" onclick="deleteBanner(${childSnapshot.key})">Eliminar Banner</button>
</p>
</div>
</div>
</div>
</div>
`;
div.insertAdjacentHTML( 'beforeend', str );
document.getElementById('inputImage'+childSnapshot.key).addEventListener('change', handleFileSelect, false);
++count;
});
});
var storageRef = firebase.storage().ref();
function handleFileSelect(evt) {
console.log("handleFileSelect(evt)");
evt.stopPropagation();
evt.preventDefault();
file = evt.target.files[0];
metadata = {
'contentType': file.type
};
storageRef.child('banners/' + file.name).put(file, metadata).then(function(snapshot) {
// Let's get a download URL for the file.
snapshot.ref.getDownloadURL().then(function(url) {
imagenBanner = url;
});
}).catch(function(error) {
console.error('Upload failed:', error);
});
}
function deleteBanner(banner) {
console.log(banner);
var result = confirm("Se borrara el banner de marketing. ¿Desea continuar?");
if (result) {
database.ref('/marketing/banners/' + banner).remove();
location.reload();
}
}
function saveBanner(banner) {
console.log(banner);
if (imagenBanner == null){
imagenBanner = "";
}
database.ref('/marketing/banners/' + banner).set({
titulo: document.getElementById("bannerTit"+banner).value,
descripcion: document.getElementById("bannerDes"+banner).value,
imagen: imagenBanner
});
location.reload();
}
function createBanner() {
if (imagenBanner == null){
imagenBanner = "";
}
database.ref('/marketing/banners/').push().set({
titulo: document.getElementById("bannerTitNew").value,
descripcion: document.getElementById("bannerDesNew").value,
imagen: imagenBanner
});
location.reload();
}
function newBanner() {
var str =`
<div class="card">
<div class="card-header" id="headingNew">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseNew" aria-expanded="true" aria-controls="collapseNew">
Nuevo Banner
</button>
</h5>
</div>
<div id="collapseNew" class="collapse show" aria-labelledby="headingNew" data-parent="#accordion">
<div class="card-body">
Introduce el banner que se mostrara al iniciar la aplicación. Especifique las imágenes y la descripción de la página.
<div style="margin: 20px 50px;">
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Titulo</span>
<input id="bannerTitNew" type="text" class="form-control" placeholder="Titulo" aria-label="Titulo" aria-describedby="Titulo">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Descripción</span>
<input id="bannerDesNew" type="text" class="form-control" placeholder="Descripción" aria-label="Descripción" aria-describedby="Descripción">
</div>
<div class="custom-file" style="margin: auto; text-align: center;">
<input type="file" class="form-control" id="inputImageNew" accept="image/*">
</div>
<p style="margin: 15px 0px; text-align: end;">
<button class="btn btn-dark" id="guardarButtonNew" class="btn btn-sm btn-outline-secondary" onclick="createBanner()">Guardar Banner</button>
</p>
</div>
</div>
</div>
</div>
`;
div.insertAdjacentHTML( 'afterbegin', str );
document.getElementById('inputImageNew').addEventListener('change', handleFileSelect, false);
}
When I click the delete button from an entry, an alert is supposed to be opened, but nothing happens.
I have checked the ids of the buttons elements and all are correct and exists in the database.
I hope that someone can help me.

Related

responsive datatables not working when we select data in dropdown

hello please help me guys to solve the problem i am facing. so here i want to insert data into datatables but using class and id because there is select function in it and in html i made an error but why error huh? it should be when we click on the data in the dropdown it will automatically appear in the table and the data will be automatically responsive`
'Use Strict';
$(document).ready(function () {
$('#tblLvl2Process').DataTable({
responsive: true,
"ordering": true,
"paging": true,
"info": true,
"bfilter": true,
"scrollx": false,
});
});
$("#selectMainProcess").change(function () {
var mainid = $(this).val();
var docid = $("#BPM_BPMDocNo").val();
var fusid = "" + mainid + "$" + docid + "";
$.ajax({
url: "/BPM/GetBPMCoreProcessList",
data: { sIdentifier: fusid },
type: "GET",
success: function (data) {
$("#selectCoreProcess").empty();
$("#selectLevel2Process").empty();
$.each(data, function (index, row) {
$("#selectCoreProcess").append("<option value ='" + row.CoreProcessCode + "'>" + row.CoreProcessText + "</ option>")
});
$('.selectpicker').selectpicker('refresh');
$(".allcorelist").hide();
$(".alllv2list").hide();
}
});
});
$("#selectCoreProcess").change(function () {
//hidden all row
$(".allcorelist").hide();
$(".alllv2list").hide();
//get core process id
var coreid = $(this).val();
var series = 1;
//dropdown level 2 type
var aListVal = [];
var aListText = [];
$("." + coreid + "").each(function () {
var codelv2 = $(this).find("#tdLevel2ProcessCode").text();
var textlv2 = $(this).find("#tdLevel2ProcessText").text();
aListVal.push(codelv2);
aListText.push(textlv2);
});
$("#selectLevel2Process").empty();
for (var i = 0; i < aListVal.length; i++) {
if (aListText[i] != "DELETE") {
$("#selectLevel2Process").append("<option value ='" + aListVal[i] + "'>" + aListText[i] + "</ option>")
}
}
$('.selectpicker').selectpicker('refresh');
//show selected
$("." + coreid + "").show();
//numbering
$.each($("." + coreid + ""), function () {
$(this).find(".num").html("" + series + "");
series = series + 1;
});
});
$("#selectLevel2Process").change(function () {
//hidden all row
$(".alllv2list").hide();
//get core process id
var lv2proid = $(this).val();
var series = 1;
//show selected
$("." + lv2proid + "").show();
//numbering
$.each($("." + lv2proid + ""), function () {
$(this).find(".num").html("" + series + "");
series = series + 1;
});
});
$("#btnSubmitNewLvl2P").click(function () {
var result;
result = $("#frmLv2P").valid();
if (result) {
var row;
$('a[href$="EDIT_Lv2P"]').off('click');
$('a[href$="DELETE_Lv2P"]').off('click');
if (sStateGridLvl2P == "-") {
var row = $('<tr id="' + $("#txtCode").val() + '" class="' + $("#txtMainCoreProcessCode").val() + ' allcorelist" >' +
'<td></td>' +
'<td class="num"></td>' +
'<td id="tdLevel2ProcessText">' + $("#txtLevel2Process").val() + '</td>' +
'<td id="tdLevel2ProcessDesc" style="white-space:pre-wrap">' + $("#txtDescription").val() + '</td>' +
'<td id="tdLevel2ProcessObj" style="white-space:pre-wrap">' + $("#txtObjective").val() + '</td>' +
'<td id="tdOtherEntity">' + $("#txtOtherEntityLv2P").val() + '</td>' +
'<td id="tdMainProcessCode" hidden>' + $("#txtMainProcessCode").val() + '</td>' +
'<td id="tdMainCoreProcessCode" hidden>' + $("#txtMainCoreProcessCode").val() + '</td>' +
'<td id="tdLevel2ProcessCode" hidden>' + $("#txtCode").val() + '</td>' +
'<td style="text-align:center;"><span class="glyphicon glyphicon-pencil"></span> <span class="glyphicon glyphicon-trash"></span></td>' +
'</tr>');
$("#tblLvl2Process tbody").append(row);
} else {
$("#tblLvl2Process").children().children()[sStateGridLvl2P].children[1].innerHTML = $("#txtLevel2Process").val();
$("#tblLvl2Process").children().children()[sStateGridLvl2P].children[2].innerHTML = $("#txtDescription").val();
$("#tblLvl2Process").children().children()[sStateGridLvl2P].children[3].innerHTML = $("#txtObjective").val();
$("#tblLvl2Process").children().children()[sStateGridLvl2P].children[4].innerHTML = $("#txtOtherEntityLv2P").val();
$("#tblLvl2Process").children().children()[sStateGridLvl2P].children[5].innerHTML = $("#txtMainProcessCode").val();
$("#tblLvl2Process").children().children()[sStateGridLvl2P].children[6].innerHTML = $("#txtMainCoreProcessCode").val();
$("#tblLvl2Process").children().children()[sStateGridLvl2P].children[7].innerHTML = $("#txtCode").val();
$("#tblStoreOtherEntityLv2P tbody").find("#" + $("#txtCode").val() + "").find("#tdOtherEntity").text($("#txtOtherEntityLv2P").val());
$.each($("." + $("#txtCode").val() + ""), function () {
var paramIME = $("#txtOtherEntityLv2P").val();
if (paramIME == "YES") {
$(this).find("#tdOtherEntity").html($("#txtOtherEntityLv2P").val());
}
});
}
$('a[href$="EDIT_Lv2P"]').on('click', function (e) {
e.preventDefault();
GoEditLv2P($(this));
});
$('a[href$="DELETE_Lv2P"]').on('click', function (e) {
e.preventDefault();
var thisvar = $(this);
BootstrapDialog.show({
title: 'CONFIRMATION',
message: 'Apakah anda yakin akan menghapus data ini ?',
type: BootstrapDialog.TYPE_WARNING, // <-- Default value is BootstrapDialog.TYPE_PRIMARY
closable: true, // <-- Default value is false
draggable: true, // <-- Default value is false
buttons: [{
label: 'YES',
cssClass: 'btn-primary',
action: function (dialogItself) {
GoRemoveLv2P(thisvar);
dialogItself.close();
}
}, {
label: 'NO',
cssClass: 'btn-danger',
action: function (dialogItself) {
dialogItself.close();
}
}]
});
});
var series = 1;
$.each($("." + $("#txtMainCoreProcessCode").val() + ""), function () {
$(this).find(".num").html("" + series + "");
series = series + 1;
});
$("#tblLvl2Process").trigger('footable_collapse_all').trigger('footable_redraw');
$("#ModalLevel2Process").modal('hide');
//change dropdown level 2 process
var coreid = $("#selectCoreProcess").val();
var aListVal = [];
var aListText = [];
$("." + coreid + "").each(function () {
var codelv2 = $(this).find("#tdLevel2ProcessCode").text();
var textlv2 = $(this).find("#tdLevel2ProcessText").text();
aListVal.push(codelv2);
aListText.push(textlv2);
});
$("#selectLevel2Process").empty();
for (var i = 0; i < aListVal.length; i++) {
if (aListText[i] != "DELETE") {
$("#selectLevel2Process").append("<option value ='" + aListVal[i] + "'>" + aListText[i] + "</ option>")
}
}
$('.selectpicker').selectpicker('refresh');
sStateGridLvl2P = "-";
$("#txtLevel2Process").val("");
$("#txtDescription").val("");
$("#txtObjective").val("");
$("#txtMainProcessCode").val("");
$("#txtMainCoreProcessCode").val("");
$("#txtCode").val("");
$("#txtOtherEntityLv2P").val("");
$("#ModalLevel2Process").modal('hide');
};
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<title>#ViewData["Title"] - Standard Template 2020</title>
<!-- favicon -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
</head>
<body class="fixed-sn kalbe-skin">
<!-- Page Wrapper -->
<div class="preloader">
<div class="loading">
<img src="~/Image/1200px-Kalbe_Farma.svg.gif" width="200">
<p class="text-center pt-4 ml-4" style="font-size : 15px; font-weight : 500;">
Loading...
</p>
</div>
</div>
<div id="wrapper">
<!-- Sidebar -->
<ul class="navbar-nav bg-gradient-primary shadow-lg sidebar sidebar-dark accordion" id="accordionSidebar" style="margin: 0px; ">
</ul>
<!-- End of Sidebar -->
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<header>
<!-- Topbar -->
<nav class="navbar navbar-expand navbar-light topbar mb-4 static-top shadow">
<!-- Sidebar Toggle (Topbar) -->
<button id="sidebarToggleTop" class=" d-md-none rounded-circle border-0 mr-3">
<i class="fa fa-bars"></i>
</button>
<!-- Sidebar Toggler (Sidebar) -->
<div class="text-center d-none d-md-inline">
<button class="border-0 toggel-nav" id="sidebarToggle">
<i class="fa fa-bars"></i>
</button>
</div>
<!-- Topbar Navbar -->
<ul class="nav navbar-nav nav-flex-icons ml-auto" id="NavbarTop">
</ul>
</nav>
<!-- End of Topbar -->
</header>
<!-- Begin Page Content -->
<div class="container-fluid box">
<!--Main Layout-->
<main role="main" class="pb-3">
<div class="container-fluid">
<div class="shadow-sm tbl-1 p-3 mb-5" style="background : #F1F1F1;">
<div class="text-left text-table">
<h3 class="ml-2 mt-2" id="labelHeader">List Operational Risk</h3>
<div class="d-flex flex-row">
<div class="p-2">
<div class="form-group selct-kalbe" id="searchEntity">
<div class="" id="labelEntity">
<label for="selectSearchEntity">ENTITY</label>
</div>
<select class="form-control input-sm" id="selectSearchEntity" data-live-search="true" data-size="10" data-width="100%">
#foreach (var item in ListEntity)
{
<option value="#item.Value">#item.Text</option>
}
</select>
</div>
</div>
<div class="p-2 mt-4 pt-3 portfolio-item" id="labelDocNo" hidden>
<div class="form-group" style="float:right">
<label class="control-label" for="selectSearchDocNo">Doc No: </label>
</div>
</div>
<div class="p-2 mt-4 pt-3 portfolio-item" id="searchDocNo" hidden>
<div class="form-group">
<div>
<input class="form-control input-sm text-box single-line" id="selectSearchDocNo" type="text">
</div>
</div>
</div>
<div class="p-2 mt-4 pt-3">
<button type="submit" id="btnReload" class="btn btn-sm btn-kalbe"><span class="glyphicon glyphicon-repeat"></span> Reload</button>
</div>
</div>
<div class="row" style="margin-left : -7px;">
<div class="col-md-4 col-sm-12">
<input placeholder="Search" class="form-control input-sm" style="border-radius : 20px" type="text" id="ListOPR" aria-label="Search">
</div>
</div>
<div class="searchFilter row pt-3" style="margin-left : -7px;">
<div class="col-md-4 col-sm-12">
<div class="form-group" id="selectSearchEntity">
<div class="" id="">
<label for="selectSearchEntity">TABLE FILTER</label>
</div>
<select class="mdb-select colorful-select dropdown-primary md-form" multiple id="searchFilterSelect" style="border-radius : 20px" data-size="10" data-width="100%" onchange="filterColumnOnChange()">
<option value="DocNo">Doc. No.</option>
<option value="RefDoc">Ref. Doc. No</option>
<option value="Entity">Entity</option>
<option value="Process">Process</option>
<option value="LastUpdate">Last Update</option>
<option value="LastRevisit">Last Revisit Status</option>
</select>
<button type="button" id="btnSelectAll" class="btn btn-sm btn-primary" onclick="SelectAll()"><span class="glyphicon glyphicon-ok"></span> SELECT</button>
<button type="button" id="btnRemove" class="btn btn-sm btn-danger" onclick="RemoveFilter()"><span class="glyphicon glyphicon-remove"></span> REMOVE ALL</button>
</div>
</div>
</div>
<div class="d-flex flex-row mt-4 ml-1">
<div class="p-2">
<button id="PICProcessInput" type="button" class="btn btn-sm btn-default btn-arrow-right rounded-pill" title="PIC Process Input">0/0</button>
</div>
<div class="p-2">
<button id="SuperiorPICProcessInput" type="button" class="btn btn-sm btn-default btn-arrow-right" title="Superior PIC Process Review">0/0</button>
</div>
<div class="p-2">
<button id="PICRMReview" type="button" class="btn btn-sm btn-default btn-arrow-right" title="PIC RM Review">0/0</button>
</div>
<div class="p-2">
<button id="PICSBUReview" type="button" class="btn btn-sm btn-default btn-arrow-right" title="PIC SBU Review">0/0</button>
</div>
</div>
<div class="d-flex flex-row mt-4 ml-1">
<div class="p-2">
<button id="PICRADevReview" type="button" class="btn btn-sm btn-default btn-arrow-right" title="PIC RA Dev Review">0/0</button>
</div>
<div class="p-2">
<button id="HeadEntityReview" type="button" class="btn btn-sm btn-default btn-arrow-right" title="Head Entity Review">0/0</button>
</div>
<div class="p-2">
<button id="Approved" type="button" class="btn btn-sm btn-default btn-arrow-right" title="Review">0/0</button>
</div>
</div>
<div class="row mt-5">
<div class="col-md-3">
<button type="button" id="btnExportLMRModal" class="btn btn-warning btn-sm" style="margin-right:10px"><span class="glyphicon glyphicon-save-file"></span> Export List Mandatory Risk</button>
</div>
<div class="col-md-3" style="margin-right: 37px;">
<button type="button" id="btnExportLRAA" class="btn btn-warning btn-sm" style="margin-right:20px"><span class="glyphicon glyphicon-save-file"></span> Export List Risk Above Tolerance</button>
</div>
<div class="col-md-3">
<button type="button" id="btnExportURR" class="btn btn-warning btn-sm" style="margin-right:10px"><span class="glyphicon glyphicon-save-file"></span> Export Updated Risk Register</button>
</div>
<div class="col-md-3">
<button type="button" id="btnExportLOR" class="btn btn-warning btn-sm" style="margin-right:0px"><span class="glyphicon glyphicon-save-file"></span> Export List Operational Risk</button>
</div>
<div class="col-md-3">
<button type="button" id="btnExportLKR" class="btn btn-warning btn-sm" style="margin-right:10px"><span class="glyphicon glyphicon-save-file"></span> Export List Key Risk</button>
</div>
<div class="col-md-3">
<button type="button" id="btnNewOR" class="btn btn-primary btn-sm divbtnNew" style="margin-right:10px; display:none"><span class="glyphicon glyphicon-file"></span> New Operational Risk</button>
</div>
</div>
</div>
#{Html.RenderPartial("Loading");}
<div class="card card-custom">
<!-- Editable table -->
<div class="card ">
<div class="card-body">
<!-- Collapse buttons -->
<!-- / Collapse buttons -->
<div class="row">
<div class="col-sm-10 col-md-12 col-lg-12 col-xs-12 col-12">
<div id="divTblListOR" class="table-responsive" style="overflow: hidden;">
<table id="tblListOR" class="table table-striped table-condensed text-left display responsive nowrap text-left" width="100%">
<thead>
<tr>
<th class="theadCollapse">Collapse</th>
<th>No</th>
<th class="theadDocNo">Doc. No.</th>
<th class="theadRefDoc">Ref. Doc. No</th>
<th class="theadEntity">Entity</th>
<th class="theadProcess">Process</th>
<th class="theadLastUpdate">Last Update</th>
<th class="theadLastRevisit">Last Revisit Status</th>
#*
<th>Supporting Document</th>*#
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Editable table -->
</div>
</div>
</div>
</main>
<!--Main Layout-->
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<!-- Footer -->
<footer class="sticky-footer page-footer">
<div class="container my-auto">
<div class="copyright text-center my-auto">
<a>© 2020 - Standard Template 2020 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</div>
</footer>
<!-- End of Footer -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Logout Modal-->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<a class="btn btn-primary" href="login.html">Logout</a>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
</body>
</html>
There are methods for DataTable() that take care of what you want to do. Note that I have changed the IDs for the new table row TD elements into classnames - because you shouldn’t duplicate id’s. Rather than do inline styles, set up a new classname prewrap
<style>
.prewrap{
white-space: pre-wrap;
}
</style>
Somewhere at the top of your script, get a reference for the DT
const t = $('#tblLvl2Process').DataTable();
and in your loop:
// to replace your TR insert in your loop -- insert the data
t.row.add( [
"",
"",
$("#txtLevel2Process").val(),
$("#txtDescription").val(),
$("#txtObjective").val(),
$("#txtOtherEntityLv2P").val(),
$("#txtMainProcessCode").val(),
$("#txtMainCoreProcessCode").val(),
$("#txtCode").val(),
'<span class="glyphicon glyphicon-pencil"></span> <span class="glyphicon glyphicon-trash"></span>'
] ).node();
// add id and class to the tr
t.id = $("#txtCode").val();
t.addClass(' + $("#txtMainCoreProcessCode").val() + ' allcorelist')
// now the tds
$(t).find('td').eq(1).addClass('num');
$(t).find('td').eq(2).addClass('tdLevel2ProcessText');
$(t).find('td').eq(3).addClass('tdLevel2ProcessDesc prewrap');
$(t).find('td').eq(4).addClass('tdLevel2ProcessObj prewrap');
$(t).find('td').eq(5).addClass('tdOtherEntity');
$(t).find('td').eq(6).addClass('tdMainProcessCode');
$(t).find('td').eq(7).addClass('tdMainCoreProcessCode');
$(t).find('td').eq(8).addClass('tdLevel2ProcessCode');
t.draw( false );
I can't test this, but that should take care of it.

jQuery slideToggle class with dynamically created id

I am trying to hide / show comment replies.
I tried a few methods but couldn't get class with dynamic ids.
My html structure is like this :
<div class="display-comments">
<div class="form-group border-bottom" id="comment-1">
//level - 1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom parentOF-1" id="comment-2">
//level-2 parentOF-1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom parentOF-2" id="comment-3">
//level-3 parentOF-2
</div>
<div class="form-group border-bottom" id="comment-4">
//level-4 doesnt have child
</div>
</div>
I tried like in the following example with different variations.
$(document).on('click', '.show_reply', function(e) {
e.preventDefault();
var commet-id = $('comment-').val();
var parentOF = $('parentOF-').val();
$(this).text() == "show replies" ? $(this).text("show replies") : $(this).text("hide replies");
$(this).closest('parentOF-').nextUntil('parentOF-').slideToggle();
});
But couldn't make it work. Thanks for any help.
You could Hide At comment div's all class that contains parentOf- class ,
$("div[class*='parentOF-']").hide();
then in each button attach event that show child comment on click , otherwise hide child comment and all it's children using recuresive function described in the snippet :
function hideRecurssive(id) {
let $child = $(`.parentOF-${id}`);
if($child.length>0) {
var newId = $child.attr("id")
// get last char that refer to child comment
newId = newId.charAt(newId.length - 1);
$child.slideUp();
var btn = $child.find(".show_reply");
if(btn.length) btn.text("show replies");
hideRecurssive(newId);
};
}
Here a working snippet as I understand :
$(function($) {
$("div[class*='parentOF-']").hide();
$(document).on('click', '.show_reply', function(e) {
e.preventDefault();
let id = $(this).attr("id");
if( $(this).text() == "show replies" ) {
$(this).text("hide replies")
let $childComment = $(`.parentOF-${id}`)
$childComment.slideDown();
} else if($(this).text() === "hide replies") {
hideRecurssive(id);
$(this).text("show replies")
}
});
});
function hideRecurssive(id) {
let $child = $(`.parentOF-${id}`);
if($child.length>0) {
var newId = $child.attr("id")
// get last char that refer to child comment
newId = newId.charAt(newId.length - 1);
$child.slideUp();
var btn = $child.find(".show_reply");
if(btn.length) btn.text("show replies");
hideRecurssive(newId);
};
}
.hide {
color: red;
}
.unhide {
color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<div id="display_comment" class="col-12">
<div class="form-group border-bottom " id="comment-6">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Google Çeviri, yabancı dili İnternet&amp;#39;teki içerik deryasını tam olarak anlamak için yeterli olmayan kullanıcılar tarafından tercih ediliyor. Bununla birlikte Google Çeviri, her zaman mükemmel t</div>
</div>
<div class="col-12 sttime">2021-01-09 02:23:38
<button type="button" class="btn btn-primary btn-xs reply" id="6">Reply <i class="fas fa-share" aria-hidden="true"></i></button> <button id="6" type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
</div>
</div>
<div class="form-group border-bottom parentOF-6" id="comment-7">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Translate aracı halihazırda 100&amp;#39;den fazla dil arasında tercüme yapıyor.</div>
</div>
<div class="col-12 sttime">2021-01-09 02:23:56
<button type="button" class="btn btn-primary btn-xs reply" id="7">Reply <i class="fas fa-share" aria-hidden="true"></i></button> <button id="7" type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
</div>
</div>
<div class="form-group border-bottom parentOF-7" id="comment-8">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Google Translate çeviriler için yakın zamana kadar Avrupa Parlamentosu ve Birleşmiş Milletler gibi büyük kuruluşların verilerini kullanıyordu. Çeviriler ayrıca sözlük bilgileri ve kullanıcılar tarafın</div>
</div>
<div class="col-12 sttime">2021-01-09 02:24:19
<button type="button" class="btn btn-primary btn-xs reply" id="8">Reply <i class="fas fa-share" aria-hidden="true"></i></button> <button id="8" type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
</div>
</div>
<div class="form-group border-bottom parentOF-8" id="comment-11">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">rew rew ew wre</div>
</div>
<div class="col-12 sttime">2021-01-09 18:10:46
<button type="button" class="btn btn-primary btn-xs reply" id="11">Reply <i class="fas fa-share" aria-hidden="true"></i></button>
</div>
</div>
</div>
<div class="form-group border-bottom " id="comment-9">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Google Çeviri nasıl kullanılır? Google Translate anlaşılır bir arayüze sahip ancak keşfedilecek birçok özelliği var.</div>
</div>
<div class="col-12 sttime">2021-01-09 02:24:43
<button type="button" class="btn btn-primary btn-xs reply" id="9">Reply <i class="fas fa-share" aria-hidden="true"></i></button>
</div>
</div>
</div>
</div>
Updated as per request. This will allow you to show nested comments and hide them. If you hide a parent comment then all nested comments will be hidden.
N.B. I changed your parentOF- to childOF- because it didn't make sense. You can just change all incidences of the class name in the code below if you'd like to keep it.
All the code is fully commented.
// Add dynamic click event listener
$(document).on('click', '.show_reply', function(e) {
// Toggle button text
if ($(this).text() == "show replies") {
$(this).text("hide replies");
} else {
$(this).text("show replies");
}
// Get comment-id from parent element
commentID = $(this).parent().attr("id");
// Just get id
commentID = commentID.replace("comment-", "");
// Store element
el = $(".childOF-" + commentID);
// Check if element is visible
if (el.is(':visible')) {
// Check for nested comments if hiding
hideNested(commentID);
// Hide element
el.slideUp();
} else {
// Show element
el.slideDown();
}
});
function hideNested(nestedID) {
// Find element that is child of the one passed
nested = $(".childOF-" + nestedID)
// Check if nested comment exists
if (nested.length == 0) {
// Exit function if it does not
return;
}
// Hide comment
nested.slideUp();
// Update button text
nested.find("button.show_reply").text("show replies");
// Check for further nested comments
hideNested(nested.attr("id").replace("comment-", ""));
}
div[class^='childOF'],
div[class*=' childOF'] {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="display-comments">
<div class="form-group border-bottom" id="comment-1">
//level - 1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
<div class="form-group border-bottom childOF-1" id="comment-2">
//level-2 childOF-1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom childOF-2" id="comment-3">
//level-3 childOF-2
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom childOF-3" id="comment-4">
//level-4 childOF-3
</div>
</div>
<div class="form-group border-bottom" id="comment-5">
//level-5 doesnt have child
</div>
</div>

How to get the text value in a div html by clicking on button

I want to get the text between the div tag by clicking on the button event
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-secondary">
<div class="price-header">
<h3 class="title text-white">Gold Plan</h3>
<div class="price">
<span class="dollar">&#8377</span> 7000
</div>
<span class="permonth">3 months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal"
class="btn btn-primary btn-block btn-lg" href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-third">
<div class="price-header">
<h3 class="title text-white">Diamond Plan</h3>
<div class="price text-primary">
<span class="dollar">&#8377</span> 12000
</div>
<span class="permonth">6 Months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal"
class="btn btn-primary btn-block btn-lg" href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-fourth">
<div class="price-header">
<h3 class="title text-white">Platinum Plan</h3>
<div class="price text-white">
<span class="dollar">&#8377</span> 15000
</div>
<span class="permonth">12 Months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal"
class="btn btn-primary btn-block btn-lg" href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
I have this type of divs its around three or four I want to detect the value 12000 and the month 6 Months by clicking on this button
How can I achieve that.
Try
$(".price-footer .btn").on( "click", function(event) {
const parent = $(this).parents('.pricing-table');
const priceText = $('.price', parent).text().trim();
const priceParts = priceText.split(' ');
console.log(`priceText: ${priceParts[1]}`);
// Output: "priceText: 12000"
const permonthText = $('.permonth', parent).text().trim();
console.log(`permonthText: ${permonthText}`);
// Output: "permonthText: 6 Months"
});
Demo - https://codepen.io/vyspiansky/pen/MWybEEr
You can add ids to the elements you want to extract the contents of, then you can use document.getElementById(id) to get those elements, and use .innerText to extract the string contents.
Then with a string.replace() you can remove any non-numerical values, and convert the monetary value into a number.
const dollarAmount = parseFloat(document.getElementById("dollar-info").innerText.replace(/[^0-9.]/g, ''))
const month = document.getElementById("month-info").innerText
console.log(dollarAmount)
console.log(month)
<div class="price-header">
<h3 class="title text-white">Diamond Plan</h3>
<div id="dollar-info" class="price text-primary">
<span class="dollar">&#8377</span>12000.80
</div>
<span id="month-info" class="permonth">6 Months</span>
</div>
Assuming you have many price tables you can loop each table as below example. You can wrap you data in a certain class and get the text value of that class div. Click the button on the to get the value in the example below
$(document).ready(function(){
$('.pricing-table').each(function(){
var $table = $(this);
$table.on('click', '.btn-primary', function(){
var price = $table.find('.price').text().trim();
var permonth = $table.find('.permonth').text().trim();
alert("price is " + price + " for " + permonth);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-third">
<div class="price-header">
<h3 class="title text-white">Diamond Plan</h3>
<div class="price text-primary">
<span class="dollar">&#8377</span> 12000
</div>
<span class="permonth">6 Months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal"
class="btn btn-primary btn-block btn-lg" href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
There are so many options to do this. Here is my example with the snippet and code sandbox.
// jquery
const findValues = (target, value) => target.parents().eq(1).find(value);
$(document).on("click", ".btn", (e) => {
const $target = $(e.target);
// dollar is optional
const $dollar = findValues($target, ".dollar");
const $value = findValues($target, ".value");
const $month = findValues($target, ".permonth");
$("#test").text(`${$dollar.text()} ${$value.text()} ${$month.text()}`);
});
// // vanilla js
const test1 = document.querySelector("#test1");
document.querySelectorAll(".btn").forEach((btn) => {
btn.addEventListener("click", ({ target }) => {
const nodes = target.parentNode.parentNode;
const dollar1 = nodes.querySelector(".dollar");
const value1 = nodes.querySelector(".value");
const month1 = nodes.querySelector(".permonth");
test1.innerText = `${dollar1.textContent} ${value1.textContent} ${month1.textContent}`;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-secondary">
<div class="price-header">
<h3 class="title text-white">Gold Plan</h3>
<div class="price">
<span class="dollar">&#8377</span> <span class="value">7000</span>
</div>
<span class="permonth">3 months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-block btn-lg"
href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-third">
<div class="price-header">
<h3 class="title text-white">Diamond Plan</h3>
<div class="price text-primary">
<span class="dollar">&#8377</span> <span class="value">12000</span>
</div>
<span class="permonth">6 Months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-block btn-lg"
href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-fourth">
<div class="price-header">
<h3 class="title text-white">Platinum Plan</h3>
<div class="price text-white">
<span class="dollar">&#8377</span> <span class="value">15000</span>
</div>
<span class="permonth">12 Months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-block btn-lg"
href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
<div id="test"></div>
<div id="test1"></div>
https://codesandbox.io/s/eager-voice-2w640?file=/src/index.js

comment reply system with catching specific id value

hi guys I have a blog post page and comment and reply system. Everything works fine except one thing:
When I try to add a reply to a comment, I am always replying to the first comment. I think my fault is I can't reach the specific comment id when I click. Here is my html and ajax code:
HTML CODE
<div class="card" style=" margin-bottom:30px;">
<div class="card-header">
<a class="h3">#Model.Header</a>
<br />
<br />
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12">
<p style="font-size:small">
<b>Kategori: </b> #Model.Category.CategoryName ,<b>Makale Sayısı :</b> #Model.Category.Articles.Count()
<b>Yorum Sayısı :</b> #Model.Comments.Count() <br />
<b>Yayımlanma Tarihi: </b> #String.Format("{0: d MMMM yyyy}", Model.Date) ,<b>Etiketler:</b><i class="fa fa-tags"></i> #Model.Tags.Count()
</p>
<p style="font-size:small;">
<img class="rounded-circle img-fluid" style="width:100px;height:100px;" src="#Model.User.Photo" alt="#Model.User.FullName" />
Posted by:
#Model.User.UserName
</p>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12">
<img id="articlephoto" style="width:100%; height:350px" class="rounded float-left" src="#Model.Photo" alt="Card image cap">
</div>
</div>
<div class="row" style="margin-top:20px">
<div class="col-md-12 col-xs-12 col-xl-12">
<p>#Html.Raw(Model.Paragraph)</p>
<p style="font-size:small">
<b>Etiketler:</b>
#foreach (var item in Model.Tags)
{
<span class="tag">#item.TagName,</span>
}
</p>
</div>
</div>
</div>
</div>
<h4>Comments</h4>
<hr />
#foreach (var item in Model.Comments.ToList())
{
<!-- Single Comment -->
<div class="media mb-4">
<img style="height:40px; width:40px;" class="d-flex mr-3 rounded-circle" src="#item.User.Photo" alt="#item.User.FullName">
<div class="media-body" style="width:400px;">
<h5 class="mt-0">#item.User.UserName</h5>
<p style="word-break:break-all">
#item.Paragraph
#if (Convert.ToInt32(Session["UserId"]) == item.UserId)
{
<a class="btn btn-danger" href="/Home/DeleteComment/#item.CommentId">
Delete
</a>
<a class="btn btn-warning replybutton" href="#replyform">
Reply
</a>
}
</p>
<p style="font-size:small"><b>Yorum Tarihi:</b>#String.Format("{0: d MMMM yyyy}", item.Date)</p>
<span id="astar" class=""> #item.CommentId</span>
#foreach (var reply in Model.ReplyComments.Where(x => x.CommentId == item.CommentId).ToList())
{
<div class="media mt-4">
<img style="height:40px; width:40px;" class="d-flex mr-3 rounded-circle" src="#item.User.Photo" alt="#item.User.FullName">
<div class="media-body">
<h5 class="mt-0">#reply.User.UserName</h5>
<p>#reply.Paragraph</p>
#if (Convert.ToInt32(Session["UserId"]) == item.UserId)
{
<a class="btn btn-danger" href="/Home/DeleteReply/#reply.ReplyCommentId">
Sil
</a>
}
</div>
</div>
}
</div>
</div>
<hr />
}
#if (Session["UserId"] != null)
{
<!-- Comments Form -->
<div id="commentform" class="card my-4">
<h5 class="card-header">Yorum Yap:</h5>
<div class="card-body">
<form>
<div class="form-group">
<textarea id="comment" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="send" class="btn btn-primary">Yorum Yap</button>
</form>
</div>
</div>
<div id="replyform" class="card my-4 d-none">
<h5 class="card-header">Cevap Yaz:</h5>
<div class="card-body">
<div class="form-group">
<textarea id="replytext" name="replytext" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="reply" name="reply" class="btn btn-primary">Cevap Yaz</button>
</div>
</div>
}
else
{
<div class="row" style="margin-bottom:30px;">
<div class="col-md-6">
<h3 class="alert- alert-heading">Yorum Yapabilmek İçin Üye Girişi Yapmalısınız.</h3>
</div>
</div>
}
AND my javascript ajax code
<script type="text/javascript">
$(document).ready(function () {
$("#reply").click(function (e) {
var r_comment = $("#replytext").val();
var r_commentid = parseInt($("#astar").html());
$.ajax({
url: '/Home/ReplyComment/',
data: { replycomment: r_comment, articleid:#Model.ArticleId, commentid: r_commentid },
type: 'POST',
dataType: 'json',
success: function (data) {
alert("Cevap gönderildi");
window.location.reload();
}
});
});
})
</script>
My problem is that I can't catch the specific comment id when I click the reply button. I am getting the comment id from <span id="astar" class=""> #item.CommentId</span>
"When I try to add a reply to a comment, I am always replying to the first comment. " - it's because all your comments have the same ID and jQuery selects the first matching element.
All comments need to have a unique ID. I don't know what language that loop is in but you need to increment the ID. So astar-1, astar-2, astar-3 etc...
Example;
$(document).ready(function(){
var valueBox = document.getElementById('value-box');
$('.reply').on('click', function(){
var comment = $(this).prev().attr('id');
valueBox.innerHTML += '<br />Reply to comment: ' + comment;
console.log(comment);
});
});
.comment::after {
display: table;
content: ' ';
clear: both;
}
span {
display: block;
float: left;
width: 45%;
}
.reply {
display: block;
float: right;
width: 45%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment">
<span id="comment-1">Yorum 1</span>
<div class="reply">Cevapla</div>
</div>
<div class="comment">
<span id="comment-2">Yorum 2</span>
<div class="reply">Cevapla</div>
</div>
<div class="comment">
<span id="comment-3">Yorum 3</span>
<div class="reply">Cevapla</div>
</div>
<div id="value-box">
</div>

Template tag in HTML: querySelector just return null value

I am making a website for education purpose as well, but I got some error that I cant figure out by myself.
I wrote a template like:
<div class="row" style="height: 75%;" align="center" id="room-list">
<template id="room-template" class="slide">
<div class="col-md-4" id="left-item">
<div class="panel panel-default panel-primary">
<div class="panel-heading">
<span id="room-type"></span>
</div>
<div class="panel-body">
<div id="thumbnail" class="thumbnail" style="width: 300px; height: 300px;"></div>
<div id="utility">
Utilities:
</div>
<div id="price">
Price:
<span id="sale" class="sale"><i class="fa fa-usd" aria-hidden="true"></i></span>
<span id="original" class="original"><i class="fa fa-usd" aria-hidden="true"></i></span>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-default btn-primary" style="width: 100%;">Book now!</button>
</div>
</div>
</div>
<div class="col-md-4" id="center-item">
<div class="panel panel-default panel-primary">
<div class="panel-heading">
<span id="room-type"></span>
</div>
<div class="panel-body">
<div id="thumbnail" class="thumbnail" style="width: 300px; height: 300px;"></div>
<div id="utility">
Utilities:
</div>
<div id="price">
Price:
<span id="sale" class="sale"><i class="fa fa-usd" aria-hidden="true"></i></span>
<span id="original" class="original"><i class="fa fa-usd" aria-hidden="true"></i></span>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-default btn-primary" style="width: 100%;">Book now!</button>
</div>
</div>
</div>
<div class="col-md-4" id="right-item">
<div class="panel panel-default panel-primary">
<div class="panel-heading">
<span id="room-type"></span>
</div>
<div class="panel-body">
<div>
<img id="thumbnail" class="thumbnail" style="width: 300px; height: 300px;">
</div>
<div id="utility">
Utilities:
</div>
<div id="price">
Price:
<span id="sale" class="sale"><i class="fa fa-usd" aria-hidden="true"></i></span>
<span id="original" class="original"><i class="fa fa-usd" aria-hidden="true"></i></span>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-default btn-primary" style="width: 100%;">Book now!</button>
</div>
</div>
</div>
</template>
</div>
And I use jquery to add that template to a append a lot of divs by using template.
var roomList = document.querySelector('template# room-list').content;
for (var i = 0; i < roomEntities.length; i++) {
var room = roomEntities[i];
var price = priceEntities[i];
var type = room.type;
var thumbnail = room.thumbnail;
var sale = price.sale;
var original = price.original;
for (var i = 0; i < 3; i++) {
var slt = "#center-item";
if (i == 0) {
slt = "#left-item";
}
else
slt = "#right-item";
var tpl = document.getElementById('room-template');
tpl.querySelector(slt + '.panel-default .panel-heading #room-type').innerText = type;
tpl.querySelector(slt + '.panel-body #thumbnail').attr('src') = thumbnail;
tpl.querySelector(slt + '.panel-body #sale').innerText = sale;
tpl.querySelector(slt +'.panel-body #original').innerText = original;
roomList.appendChild(tpl.content.cloneNode(true));
}
}
But it always returns error at tpl.querySelector(slt + '.panel-default .panel-heading #room-type').innerText = type; it said Cannot set property innerText of null, it mean cannot find the element in template.
Any advice or recommended. Please help. Many thanks
Change all Selectors in your Code
tpl.querySelector(slt + '.panel-default .panel-heading #room-type').innerText
tpl.querySelector(slt + ' .panel-default .panel-heading #room-type').innerText

Categories