Does jquery or javascript execute when loaded dynamically on an event? - javascript

I have a dropdown and when i choose an option it will load an appropriate table from the server and display it using jQuery, along with the table i also send a tiny jQuery script like,
<table id="dataFileTableHeader">
<thead>
<tr>
<th><strong>Export Type</strong></th>
<th><strong>Company</strong></th>
<th><strong>File Name</strong></th>
<th><strong>Date Modified</strong></th>
<th><strong>Total Records</strong></th>
<th><strong>File Size</strong></th>
<th><strong>Owner</strong></th>
</tr>
</thead>
</table>
<script>
$(function(){
var i = 0;
$('#dataFileTableHeader th').each(function(index) {
alert("hello " + (++i));
});
});
</script>
when this is loaded i am expecting alert to show up 7 times but nothing happens am i missing something?

DEMO
You have a space after your id
(<table id="dataFileTableHeader "> instead of <table id="dataFileTableHeader">
So this one is correct
<table id="dataFileTableHeader">
<thead>
<tr>
<th><strong>Export Type</strong></th>
<th><strong>Company</strong></th>
<th><strong>File Name</strong></th>
<th><strong>Date Modified</strong></th>
<th><strong>Total Records</strong></th>
<th><strong>File Size</strong></th>
<th><strong>Owner</strong></th>
</tr>
</thead>
</table>
<script>
$(function(){
var i = 0;
$('#dataFileTableHeader th').each(function(index) {
alert("hello " + (++i));
});
});
</script>
You can also just use the index in the alert to grab the number. You don't need "i"

If your content is dynamically loaded, the script is probably being run before the content gets there. Have this code after your "success" parameters in your ajax function (hard to say without seeing that code). Make sense?

Related

Why doesn't my partial view render <tr> elements?

So I'm trying to create a table, where the table rows being divs that I've constructed from data that I get from my database.
I've seem to run into a issue.. I got this piece of javascript that starts running as soon as the page is ready, and it runs over and over again each 10 seconds. The purpose of this script is to update the partial view using ajax so that I don't have to refresh the browser to see changes in the table.
<script type="text/javascript">
$(document).ready(function () {
setInterval(CheckAvailability, 10000);
setTimeout
});
function CheckAvailability() {
$.ajax({
type: "POST",
url: "/Dashboard/CheckChange",
contentType: "application/json; charset=utf-8",
dataType: "json",
mimeType: "text/html",
success: function (response) {
if (response) {
$('#itemsss').load("/Dashboard/ReturnItems");
console.log("Updated!");
}
else {
console.log("Failed!");
}
}
});
};
</script>
This returns true every single time because it's something I've set explicitly.
It does load(); the content that this action returns though.
public IActionResult ReturnItems()
{
Items = new List<EbayProduct>();
using (var ctx = new UserContext())
{
Items = ctx.Users.Include(x => x.Items).Where(x => x.Username == "Admin").FirstOrDefault().Items;
}
return PartialView("_Item", Items);
//return null;
}
This is where I load the PartialView
<div id="itemsss">
<table id="foo-filtering" class="table table-bordered table-hover toggle-circle" data-page-size="7">
<thead>
</thead>
<tr>
<td>
<partial name="_Item" />
</td>
</tr>
<tfoot>
<tr>
<td colspan="5">
<div class="ft-right">
<ul class="pagination"></ul>
</div>
</td>
</tr>
</tfoot>
</table>
</div>
And this is what the actual PartialView looks like
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<div class="container-1">
<div class="box-img">
<img src="#item.ProductImage" />
</div>
<div class="body">
<h3>#item.ItemName</h3>
<p>#item.SubTitle</p>
</div>
<div class="box-button">
<p>#item.SKU</p>
</div>
<div class="box-button">
<p class="mt-3 mr-2">$#item.Price</p>
<button class="btn btn-primary">Export</button>
</div>
</div>
</td>
</tr>
}
</tbody>
And here is where the issue occurs.. When I first load the page, it all works fine, it looks great and it works perfectly, but as soon as it does the first refresh.. Or .load();.. It suddenly stops working correctly, and by that I mean that it doesn't load any <tr> elements.
This is what the DOM looks like when I first load the page and it hasn't refreshed yet, each td contains the div with the class container-1 so it works just fine
And here is what it looks like after the first refresh and every single refresh after that
The jQuery call $('#itemsss').load("/Dashboard/ReturnItems") replaces existing content of the container with new elements - jQuery documentation states it as
.load() sets the HTML contents of the matched elements to the returned data.
Replacing the innerHTML of #itemsss wipes out the table element. Because <tbody>, <tr> and <td> tags are invalid outside a table, the parser ignores them, leaving #itemsss containing <div> elements only, as shown in the second picture.
If successful AJAX calls are intended to update the whole table the server could send complete HTML for the table, which could then be used to replace the content of #itemss, as shown in the post. Since picture 1 shows multiple tbody elements I assume this is not the case.
I tried appending tbody html to the table under different conditions: with or without a header and with or without existing table sections. Warning I am not a jQuery programmer - if useful, integrate and modify as best suited:
"use strict";
function appendTableBody( bodyHTML) {
let previous = $("#foo-filtering > tbody").last();
if( !previous.length) {
previous = $("#foo-table > thead").last();
}
if( previous.length) {
previous.after( bodyHTML);
}
else {
$("#foo-filtering").prepend( bodyHTML)
}
}
appendTableBody("<tbody><tr><td>appended section<\/td><\/tr><\/tbody>", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- body-html -->
<table id="foo-filtering">
<thead>
<tr><th>Table Header</th></tr>
</thead>
<tbody>
<tr><td>Table section 1</td></tr>
</tbody>
<tbody>
<tr><td>Table section 2</td></tr>
</tbody>
<tfoot>
<tr><th>table footer</th></tr>
</tfoot>
</table>
I didn't try to replace an existing tbody element, but assume it would involve selecting the element and calling the .html() method.

How to remove <br> and everything after that?

If I do the following is fine:
<div id="results">
<p>Hello<br>there</p>
</div>
$($("#results p").children('br').get(0).nextSibling).remove();
I get: hello
But if I do:
<th class="infobox">Head</th>
<td>Hello<br>there</td>
var newLineRemove = $(".infobox td").children('br').get(0).nextSibling();
$wikiDOM.find(newLineRemove).remove();
Gives me
Uncaught TypeError: Cannot read property 'nextSibling' of undefined
That is because .get(...) returns a DOM element not a jQuery object.
In the first example you're using $(...) to convert that DOM element to a jQuery object but you're not doing that in the second example.
This will convert the DOM element to a jQuery element and get rid of the error
var newLineRemove = $($(".infobox td").children('br').get(0).nextSibling);
But it won't do what you want it to do because as #Forty3 said "the <td> isn't inside the ..infobox"
This seems to work but I've probably made things more complicated then they have to be:
$(function(){
var td = $(".infobox").next();
if(td.find("br").length){
$(td.contents().get().reverse()).each(function(){
$(this).remove();
if(this.tagName == "BR"){
return false;
}
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<th class="infobox"></th>
<td>Hello<br>there</td>
</table>
I've simplest solution for this, try this one:
$('td').each(function() {
$(this).html($(this).html().split('<br>')[0]);
});
li {
margin-bottom: 10px;
}
#usp-custom-3 {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
<th class="infobox"></th>
</tr>
<tr>
<td>Hell
<br>there</td>
</tr>
<tr>
<td>Hello
<br>there<br>there</td>
</tr>
</table>
Your code doesn't work because the ".infobox td" selector is looking for a td element inside an .infobox element, but in your HTML the td immediately follows the .infobox.
If you want something that is very similar to your existing JS but working with that HTML (noting that td and th elements need to be inside a tr in a table) you can do this:
$($(".infobox").next().children("br")[0].nextSibling).remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<th class="infobox"></th>
<td>Hello<br>there</td>
</tr>
</table>
That is, use .next() to get the element following the .infobox, get that element's child br elements, take the first one's .nextSibling, then wrap it in a jQuery object so that you can call .remove().
EDIT: Note that if there were multiple rows with similar elements the above code would only do the removal on the first one. If it were my code I would probably select all of the relevant elements and then update their HTML something more like this:
$(".infobox").next("td").html(function(i, h) { return h.split('<br>')[0] })

Show a row's information into a right side div by clicking a table's row using jquery

For my recent project, I need to show data in a table. When I click on any row of the table, all the contents of the row will be shown in an additional div. See the code below:
<div class="left-side">
<table id="data">
<tr>
<td>cell(1,1)</td>
<td>cell(1,2)</td>
<td>cell(1,3)</td>
</tr>
<tr>
<td>cell(2,1)</td>
<td>cell(2,2)</td>
<td>cell(2,3)</td>
</tr>
<tr>
<td>cell(3,1)</td>
<td>cell(3,2)</td>
<td>cell(3,3)</td>
</tr>
</table>
</div>
<div class="right-side">
<!-- when a row is clicked, then the respective information is shown here-->
<!-- for example, if i click the first row, then it shows cell(1,1) and cell(1,2) and cell(1,3) and so on-->
</div>
Please suggest any idea of how to do it using jQuery or JavaScript.
var string = '';
$("#data tr").click(function() {
$(this).find("td").each(function(index) {
string += $(this).text();
});
document.write("<br/>" + string);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left-side">
<table id="data">
<tr>
<td>cell(1,1)</td>
<td>cell(1,2)</td>
<td>cell(1,3)</td>
</tr>
<tr>
<td>cell(2,1)</td>
<td>cell(2,2)</td>
<td>cell(2,3)</td>
</tr>
<tr>
<td>cell(3,1)</td>
<td>cell(3,2)</td>
<td>cell(3,3)</td>
</tr>
</table>
</div>
<div class="right-side"></div>
Add a click event handler to your jQuery code:
<script type="text/javascript">
$(function() {
$("#data tr").click(function() { //Click event handler for the table column
var columnText = $(this).text(); //text from the column clicked.
$(".right-side").text(columnText); //Populates the .right-side div with the text.
});
});
</script>
Tip: If you know jQuery, then prefer jQuery over plain JavaScript. It'll lead to a much cleaner and concise code.
Just add a click function to your eg:
function showInrightDif(this)
{
var divtext=''
$(this).find('td').each(function() {
divtext = divtext + $(this).text;
});
$('.right-side').text(divtext);
}
add this code :
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$('#data tr').click(function () {
$('.right-side').text($(this).text());
});
</script>

Binding Click event after append Jquery not working

I've got a modal box that pops up popups when the plus icon is clicked in a table. After the page is loaded five rows are displayed in the table and clicking the plus sign opens the modal box. (Works perfectly).
But now we are changing the content of the table by an AJAX call. Once the TR's are replaced by new ones, the plus signs aren't working any more.
I'm aware of the fact that the event-handler
Table:
<table class="table table-hover" id="carsTable">
<thead>
<tr>
<th>Car Title</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr id="car-1836">
<td>ferrari f50</td>
<td><i class="glyph-icon icon-plus-circle">+</i></td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Product Title</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
The Jquery Part that handles the AJAX (and works, replaced the table according to the JSON respons).
$.post("../../../scripts/getCars.php", {s: carSearch}, function (data) {
$("tr[id='carLoader']").remove();
$.each(data, function (index) {
if ($('#selectedCar-' + data[index].externalProductId + '').length == 0) {
$('#carsTable')
.append('<tr id="car-'+ data[index].id+'"><td>' + data[index].title + '</td><td><i class="glyph-icon icon-plus-circle"></i></td></tr>');
}
});
}, "json");
Now the event Handler, works after document is ready, but stops working once the AJAX call has replaced the data.
$('#carsTable').on('click', '.black-modal-80', function () {
console.log('Click detected; modal will be displayed');
});
What's wrong with the binding?
When you append something to the window, the element doesn't exist until you run the jQuery. That means the element the click event points to doesn't exist when the click event is defined. So you can use the body as a selector like this.
$('body').on('click', '.black-modal-80', function () {
console.log('Click detected; modal will be displayed');
});
Hope this helped!

Check All box does not work with Jquery DataTable version 1.10.5

I have a jquery dataTable with 3 columns (check box column, userId, full name). The 'check_all' check box worked fine (meaning all the rows were checked when the 'check_all' was clicked) when I used it with jquery.dataTables.js and jquery.dataTables.min.js version 1.9.4. However, I have to use dataTable version 1.10.5 in order to use the "draw()" function. But once I started using the new version, the check_all checkbox stopped working, the alert() inside the .click() didn't get invoked. I tried to put the .click function inside the $(document).ready(), but didn't fix the issue. Anybody has any idea ? Thanks!!
Script:
$('#check_all').click(function()
{
alert("here");
var oTable = $('#users').DataTable();
});
HTML part:
<DIV id ="tablePanel">
<table class="userTable" cellpadding="4" rules="all" border="1" id="users">
<THEAD>
<TR>
<th><input type="checkbox" id ="check_all" class="call-checkbox" name="check_all">Select users</th>
<th>User Id</th>
<th>Full Name</th>
</TR>
</THEAD>
<TBODY>
<TBODY>
</table>
</DIV>
You are missing the closing ")" on the click event handler function. You should also ensure that any bindings occur after the DOM is ready by placing them inside jQuery's document.ready() function.
The full syntax is $(document).ready(function () { .. }); but it can be shortened to $(function() { ... });
$(function () {
$('#check_all').click(function () {
alert("here");
var oTable = $('#users').DataTable();
});
});
Demo: http://jsfiddle.net/BenjaminRay/qe0ckve8/

Categories

Resources