How to bind table id to DOM in ajax success function - javascript

In my project, I want to do something when checkbox is clicked.
Here is my code which works OK:
<script>
window.onload=function()
{
var uTId = document.getElementById('uTId');
uTId.addEventListener("click", function(ev){
if(ev.target.getAttribute("type") == "checkbox"){
alert("xietest");
}
},false);
}
</script>
<div class="easyui-panel" id="pp" >
<table class="uTb" id="uTId" cellspacing="0" style="100%" >
<tr>
<td ><input type="checkbox" id="Jack"/>Jack</td>
</tr>
</table>
</div>
And "xietest" can be appeared in page successfully when checkbox is clicked;
But actually the content of pp easyui-panel is from ajax , like:
<script>
...
$.ajax({
.......
success:function(data){
var drfV='<table class="uTb" id="uTId" cellspacing="0" style="100%" >';
drfV=drfV+'<tr><td ><input type="checkbox" value="'+data.name+'"/>'+data.name+'</td>';
drfV=drfV+'</tr></table>';
$('#pp').html("");
$('#pp').append(drfV);
}
});
....
window.onload=function()
{
var uTId = document.getElementById('uTId');
uTId.addEventListener("click", function(ev){
if(ev.target.getAttribute("type") == "checkbox"){
alert("xietest");
}
},false);
}
</script>
<div class="easyui-panel" id="pp"></div>
Now It works fail, "xietest" can not show like before.
I know that table id uTId should not be found in DOM as it was loaded after window onload.
But I don't know how to bind table id uTId to DOM, Who can help me?

As you said, you can't declare an event for unloaded dom element yet. You should handle all success events and define the event after. So, you could use setInterval to apply it.
var ajax1Success = true;
var ajax2Success = true;
success: function(data) {
var drfV = '<table class="uTb" id="uTId" cellspacing="0" style="100%" >';
drfV = drfV + '<tr><td ><input type="checkbox" value="' + data.name + '"/>' + data.name + '</td>';
drfV = drfV + '</tr></table>';
$('#pp').html("");
$('#pp').append(drfV);
//Declare the event
ajax1Success = true;
}
success: function(data) {
var drfV = '<table class="uTb" id="uTId" cellspacing="0" style="100%" >';
drfV = drfV + '<tr><td ><input type="checkbox" value="' + data.name + '"/>' + data.name + '</td>';
drfV = drfV + '</tr></table>';
$('#pp').html("");
$('#pp').append(drfV);
//Declare the event
ajax2Success = true;
}
var t = window.setInterval(function () {
var ajaxSuccess = ajax1Success || ajax2Success;
if (ajaxSuccess == true) {
clearInterval(t);//Clear the interval after at least one ajax call have been succeeded
var uTId = document.getElementById('uTId');
uTId.addEventListener("click", function (ev) {
if (ev.target.getAttribute("type") == "checkbox") {
alert("xietest");
}
});
}
}, 1000);

Related

build unique table with JQuery AJAX

I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.
The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table
JSON1:
[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]
JSON2:
[{"GLComment":"comment from table 2","EnComment":""},
{"GLComment":"","EnComment":""}]
I have tried doing this to append to my existing table
var tblSomething = document.getElementById("table1");
<table class="table 1">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
//table does not get built here only for table 1
<table class="table 2">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
<script>
//this only works for table1
$(document).ready(function() {
infoTableJson = {}
buildInfoTable();
});
function buildInfoTable(){
$.ajax({ //allows to updates without refreshing
url: "comment1.json", //first json file
success: function(data){
data = JSON.parse(data)
var tblSomething = '<tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td data-key="' + key + '">' + value + '</td>';
});
//tblSomething += '<td><button class="editrow"></button></td>'
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('.table').append(tblSomething)
$('.table td').on('click', function() {
var row = $(this).closest('tr')
var index = row.index();
var comment = row.find('td:nth-child(1)').text().split(',')[0]
var engcomment = row.find('td:nth-child(2)').text().split(',')[0]
var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
var newDialog = $("<div>", {
id: "edit-form"
});
newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Edit',
height: 350,
width: 350,
modal: true,
autoOpen: false,
buttons: [{
text: "Save",
click: function() {
console.log(index);
user = $.cookie('IDSID')
var today = new Date();
var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
//FIXME
var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
// update data
data[index].GLComment = comment;
data[index].EngComment =engcomment;
$.ajax({
type: "POST",
url: "save.asp",
data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
success: function(){},
failure: function(errMsg) {
alert(errMsg);
}
});
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
}
</script>
The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.
$(document).ready(function() {
// call the function and pass the json url
buildInfoTable("comment1.json");
buildInfoTable("comment2.json");
// Just to disable the snippet errors for this demo
// So the ajax aren't done
// No need to run the snippet :D
$.ajax = ()=>{}
});
function buildInfoTable(jsonurl){
$.ajax({
url: jsonurl,
success: function(data){
data = JSON.parse(data)
// Clone the prebuild table
// and remove the prebuild class
var dynamicTable = $(".prebuild").clone().removeClass("prebuild");
// Loop the json to create the table rows
$.each(data, function(idx, obj){
rows = '<tr>';
$.each(obj, function(key, value){
rows += '<td data-key="' + key + '">' + value + '</td>';
});
rows += '</tr>';
});
// Append the rows the the cloned table
dynamicTable.find("tbody").append(rows)
// Append the cloned table to document's body
$("body").append(dynamicTable)
}
})
}
</script>
/* This class hides the prebuid table */
.prebuild{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
<tbody>
</tbody>
</table>

how to get the value of the clicked table row?

My question is: how do I get the value of the clicked row and column?
The code I have is this:
JS:
$.ajax({
type: 'POST',
url: url,
data: json,
success: function(data) {
var response_array = JSON.parse(data);
var columns = ['id', 'name', 'email', 'telephone', 'website', 'city'];
var table_html = ' <tr>\n' +
'<th id="id">Id</th>\n' +
'<th id="name">Bedrijfnaam</th>\n' +
'<th id="email">E-mail</th>\n' +
'<th id="telephone">Telefoon</th>\n' +
'<th id="website">Website</th>\n' +
'<th id="city">Plaats</th>\n' +
'</tr>';
for (var i = 0; i < response_array.length; i++) {
//create html table row
table_html += '<tr>';
for (var j = 0; j < columns.length; j++) {
//create html table cell, add class to cells to identify columns
table_html += '<td class="' + columns[j] + '" >' + response_array[i][columns[j]] + '</td>'
}
table_html += '</tr>'
};
$("#posts").append(table_html);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
Here is the HTML:
<div class="tabel">
<table id="posts">
</table>
</div>
I have tried the following:
$('#posts').click(function(){
console.log("clicked");
var id = $("tr").find(".id").html();
console.log(id);
});
Sadly this will only give me the id of the first row, no matter where I click.
Any help is appreciated!
Ramon
The below approach should be able to find the ID
$('#post').on('click', function(e){
var id = $(e.target).closest('tr').find(".id").html();
console.log(id)
})
HTML content of clicked row
$('#posts tr').click(function(){
$(this).html();
});
text from clicked td
$('#posts tr td').click(function(){
$(this).text();
});
If you are using ajax and you are redrawing elements, you will not catch em via click function. You will need to add on function:
$(document).on('click','#posts tr td','function(){
$(this).text();
});
You may try to use AddEventListener for your table, it will work for sure.
Like this:
let posts = document.getlementById('posts');
posts.addEventListener('click',(e) => {
// anything you need here, for example:
console.log(e.target);
e.preventDefault();
});
As well - it will be fine not to use same IDs for elements in a grid (like id="id" which you have), it should be different.

JavaScript alert on click event if no checkboxes are checked

Every thing works normally except when I check all the rows and try to delete them with a button.
I put an alert in the delete button which tests if any rows are checked, so when I click the button and no boxes are checked, it shows the alert.
Also when all the boxes are checked how do I change it or where do I put it?
I am new to JavaScript and php.
Or can I change it to a delete confirmation alert!
Here is my code .
<script>
function checkUncheckAll(){
var chks = document.getElementsByName("ck");
if(document.getElementById("ck_All").checked)
{
$("#delete_link").on("click" , deleteSelectedRows);
for( i = 0;i < chks.length;i++)
document.getElementsByName("ck")[i].checked = true;
}
else {
for( i = 0;i < chks.length;i++)
document.getElementsByName("ck")[i].checked = false;
document.getElementById("delete_link").onclick = function(){deleteSelectedRows();};
}
}
function selectUnselect(checked){
if(!checked)
document.getElementById("ck_All").checked = false;
else {
document.getElementById("delete_link").onclick = function(){deleteSelectedRows();};
var chks = $("input[name='ck']");
var all_checked = true;
for(i=0;i<chks.length;i++)
if(chks[i].checked)
continue;
else {all_checked = false; break;}
if(all_checked)
document.getElementById("ck_All").checked = true;
}
}
function deleteSelectedRows(){
var cks = $("input[name='ck']");
var checked = [];
for(i = 0;i<cks.length;i++)
if(cks[i].checked)
checked.push(cks[i].parentNode.parentNode.id);
var jsonob = JSON.stringify(checked);
$.post("deletecom.php" , {rows_to_be_deleted:jsonob} , function(data){
for(i=0;i<checked.length;i++)
$("#" + checked[i]).fadeOut('slow' , function(){$(this).remove();});
});
}
</script>
<a id="delete_link" onclick="alert('Aucune case n est cochée')">Supprimer</a>
<br><br>
<?php
$con = new mysqli('localhost' , 'root' , 'etud' , 'responses');
echo "<div id='divtable'>";
echo '<table class="table" >';
echo '<tr id="throws">
<th><input id="ck_All" type="checkbox" onchange="checkUncheckAll()" />Select</th>
<th>Nom</th>
<th>Email</th>
<th>Sujet</th>
<th>Messages</th>
<th>Date Creation</th>';
// if (isset($_POST['date'])& isset($_POST['btncherche'])) {
error_reporting(E_PARSE);
$datechoosen=$_POST['date'];
$result = $con->query("select * from tb_cform where datecreation='".$datechoosen."'");
while($row = $result->fetch_assoc())
echo '<tr id="' . $row['id'] . '">
<td><input name="ck" onchange="selectUnselect(this.checked)" type = "checkbox" /></td>
<td>' . $row["u_name"] .'</td>
<td> '. $row["u_email"] . '</td>' .
'<td>' . $row["subj"] . '</td>' .
'<td>' . $row["message"] . '</td>' .
'<td>' . $row["datecreation"] . '</td>' .
'</tr>';
echo '</table>';
echo "</div>";
/* }else{
echo "veuillez choisir la date S.V.P !";
}*/
?>
When I click the delete button the alert keeps showing no matter what the condition is, help me please!
One thing I must point out is that it is best to keep your click event handlers out of your HTML and bundled with the rest of your JavaScript, see Why is using onClick() in HTML a bad practice?.
Please see my working example on JSFiddle: https://jsfiddle.net/fL91x2am/23/
Working code:
<script>
function deleteSelectedRows(){
var cks = $("input[name='ck']");
console.log(cks.length);
var checked = [];
// Add ids of checked messages to checked array
for(i = 0;i<cks.length;i++){
if(cks[i].checked){
checked.push(cks[i].parentNode.parentNode.id);
}
}
// AJAX delete POST
var jsonob = JSON.stringify(checked);
$.post("deletecom.php" , {rows_to_be_deleted:jsonob} , function(data){
for(i=0;i<checked.length;i++){
// hide deleted messages row if delete POST successful
$("#" + checked[i]).fadeOut('slow' , function(){
$(this).remove();
});
}
});
}
function checkUncheckAll(){
// var chks = all checkboxes
var chks = document.getElementsByName("ck");
// if select all checkbox is checked
if(document.getElementById("ck_All").checked) {
for( i = 0;i < chks.length;i++ ){
document.getElementsByName("ck")[i].checked = true;
}
} else {
for(i = 0;i < chks.length;i++){
document.getElementsByName("ck")[i].checked = false;
}
}
};
function selectUnselect(checked){
if(!checked){
document.getElementById("ck_All").checked = false;
} else {
document.getElementById("delete_link").onclick = function(){
deleteSelectedRows();
};
var chks = $("input[name='ck']");
var all_checked = true;
for(i=0;i<chks.length;i++){
if(chks[i].checked){
continue;
} else {
all_checked = false;
break;
}
}
if(all_checked){
document.getElementById("ck_All").checked = true;
}
}
}
// Here we use jQuery's document ready event listener to add the click event listener to #delete_link.
$(document).ready(function(){
$('#delete_link').on('click', function(){
// (jQuery syntax) - check if number of checked inputs with name attribute of 'ck' is zero
if($('input[name="ck"]:checked').length === 0){
alert('Please select an item!');
} else {
// or confirm if the user really wants to delete
var warning = confirm("Are you sure you want to delete?");
if (warning == true) {
deleteSelectedRows();
}
}
});
})
</script>
<a id="delete_link">Supprimer</a>
<br><br>
<div id="divtable"><table class="table">
<tr id="throws">
<tr><th><input id="ck_All" type="checkbox" onchange="checkUncheckAll()" />Select</th>
<th>Nom</th>
<th>Email</th>
<th>Subject</th>
<th>Messages</th>
<th>Date Creation</th></tr>
<tr id="1">
<td><input name="ck" onchange="selectUnselect(this.checked)" type = "checkbox" /></td>
<td>Name</td>
<td>Email</td>' .
<td>Subject</td>
<td>Lorem ipsum dolor</td>
<td>2017-01-01</td>
</tr>
<tr id="2">
<td><input name="ck" onchange="selectUnselect(this.checked)" type = "checkbox" /></td>
<td>Name</td>
<td>Email</td>' .
<td>Subject</td>
<td>Lorem ipsum dolor</td>
<td>2017-01-01</td>
</tr>
</table>
</div>

checkboxes and number fields set by jquery appear for a split second, then suddenly disappear

I created a simple html file that makes ajax requests to get data from a database table.
Some columns are not updated through ajax. They are manually given inputs in this page. As every ajax call refreshes the page data, I wrote storeVars() and putVars() to store the input values before refreshing and to set the stored values after refreshing respectively. But this doesn't work :(
JavaScript:
function createList() {
$.ajax({
type: "POST",
url: "fetch_registered_list.php?event_id=1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#table_data tr').not(':first').remove();
if (data != '' || data != undefined || data != null) {
var html = '';
$.each(data, function(i, item) {
html += "<tr><td>" + data[i].sno + "</td>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].email + "</td>" + "<td>" + data[i].phone + "</td>" + "<td><input class='check' name='" + i +
"' type='checkbox'/></td>" + "<td><input class='score' name='" + data[i].email + "' type='number'/></td></tr>"
})
$('#table_data tr').first().after(html);
}
}
});
}
$(document).ready(function() {
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
var checkboxes = new Array();
var scores = new Array();
function storeVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
$(this).find('.check').prop('checked', true);
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
$(this).find('.score').val('44');
});
}
HTML:
<body>
<div id="wrapper">
<div id="heading">
<h1>Event One</h1>
</div>
<form method="post">
<table id="table_data">
<tr>
<td><strong>S.no.</strong></td>
<td><strong>Name</strong></td>
<td><strong>Email</strong></td>
<td><strong>Phone</strong></td>
<td><strong>Participated</strong></td>
<td><strong>Score</strong></td>
</tr>
</table>
<footer>
<input id="button" type="button" name="submit" value="Announce Winners" />
</footer>
</form>
</div>
</body>
First, you must reset your arrays at each new storage, or you'll have arrays with exponentional new entries. Secondly your putVars() function is incorrect, it must check the values of each arrays in order to recreate the correct data in the corresponding input.
So update your document ready function to declare your two arrays.
$(document).ready(function() {
var checkboxes,
scores;
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
Then reset your two arrays every storage.
function storeVars() {
checkboxes = new Array();
scores = new Array();
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
Finally update your putVars() function like this.
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function(index) {
if(checkboxes[index] == true) {
$(this).find('.check').prop('checked', true);
}
else {
$(this).find('.check').prop('checked', false);
}
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function(index) {
$(this).find('.score').val(scores[index]);
});
}
working fiddle

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

Categories

Resources