JQuery .each() on dynamically created data from pageload - javascript

I have rows generated in a table dynamically. I am getting the data for the dynamic rows by ajax calls. This loading of dynamic rows is happening at the time of page load. I am not able to access this dynamic data using Jquery. To be specific, I need to iterate through all the rows in the table.Is there a good way to accomplish this?
Also There is no event like button click to load the data. The data is loaded at the time of page loading.
$.ajax({
type: "POST",
url: serviceUrl,
contentType: "application/json",
data: ko.toJSON(getevent),
dataType: "json",
success: function (data) {
$(".childrenrow").each(function(){ //.childrenrow are the dynamically generate table rows
alert("Here"); //This part is not getting exeucuted
//I am planning to check for the the existence of data.children in each .childrenrow once the loop is entered
});
},
error: function () {
}
});

Try this,
As you said your data will be loaded while page load then you can access those data from following code:
$(document).ready(function(){
$("table tr td").each(function(){
alert($(this).text());
});
});
This will iterate through each td of each tr and .text() will return the data inside respective td. You can also use $("table tr").each(function(){ , which will get the data from each tr.
Working js code

Related

Attach jquery events to dynamically created elements (jquery load php file)

I have a php employee directory website that lists all our employees in a table (connected to mysql), and you are able to click each employee to open up their details in another div.
$('.emptab').click(function(event) {
var status = $(this).attr('id');
$("#empview").load("employee.php", {'data': datastring, 'current': status});
});
I originally had the above code, but needed to be able to attach events to dynamic elements, so I changed to the following code:
$('tbody').on('click', 'tr.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});
I did it that way as I read in another question (In jQuery, how to attach events to dynamic html elements?) that you can use that format to attach events to dynamic elements. Just to clarify, this code continues to work with the initial page, but fails after the search filter is used.
My dynamic elements comes from a filter/search function I have that will change the list of employees based on a search text box which changes the list of employees based on a filter.php document I created.
$('#search').on('input propertychange paste', function() {
var string = $('#search').val();
$("#employeelist").load("filter.php", {'data': datastring, 'search': string});
});
However, when those elements are created from that php file, I am unable to access the elements through my jquery, I'm not sure what I'm doing wrong. There were about 4 other questions I saw where the answer was to use the jquery on function, which I've tried with no success.
Thanks for your time.
You can use following code for this
$(document).on('click', '.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});

Passing loop data as variable from JavaScript to AJAX via Bootstrap modal

My code below was used to retrieve records from a loop using JavaScript. Everything works fine. Each of the records button has a unique id that when click
should alert users_id in a Bootstrap Modal popup.
The problem is that the looped button that contains users_id is not alerting anything when each button is clicked.
Below is the code for retrieving records in JavaScript along with Bootstrap modal button:
<script>
$(document).ready(function () {
$.post('users.php', function(response){
$.each(JSON.parse(response).items, function(i,v) {
$('.userslist').append('<span>'+v.id+'</span> Profile');
});
});
});
</script>
Below is the code for posting the users_id and then alert it:
<script>
$(document).ready(function(){
$(".modalLink").click(function() {
var id = $(this).attr("id");
alert(id);
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(data) {
$("#rmm").html(data);
}
});
});
});
</script>
but if I take the Modal button outside the retrieve records in a javascript loop
it will alert users_id and everything will work fine as in code below
Profile
Can someone help me make each of the JavaScript looped button to post its own unique users_id and then alert it in a Bootstrap modal popup. I have attached a screen shot of the result obtained from the JavaScript loop.
Thanks
If I understand your question properly;
Try changing
$(".modalLink").click(function() {
to
$(document).on('click', '.modalLink', function() {
Without seeing the rest of your code or a working fiddle, I suspect your content is dynamic and JQ cannot bind the click handler, simply because there is no content to bind to. this answer does a good job of explaining the difference between .on and .click.
If you get the expected result, I would drop the document selector and use the closest parent static element.

Applying jQuery to HTML elements loaded in by ajax

I am using the jQuery plugin DataTables to spruce up my generic html tables. I can use
<script>
$(document).ready(function() {
$('table.display').DataTable();
} );
</script>
To load the DataTables plugin for all pages on the page after it loaded, but it doesn't retroactively work on any tables added through AJAX (because the page has already been loaded at that point).
How do I make sure that the
$('table.display').DataTable();
Is run on the table added to the page as well?
You can try adding a ready() event listener in jQuery to act when each <table> is loaded (rather than when the document is loaded).
Just add another block, similar to what you have:
$('table.display').ready(function() {
$(this).DataTable();
});
You can add a listener for new DOM nodes, and call the .DataTable() function if the newly added node matches table.display:
$(document).on('DOMNodeInserted', 'table.display' function(e) {
$(this).DataTable();
});
Because the DataTable function must be called on an existing element, there doesn't seem to be a way for you to have all new table.display elements automatically get instantiated with by plugin. Try instantiating the new elements in your AJAX success callback:
$.ajax({
url: '/your/url',
type: 'POST',
success: function (data) { $('table.display').DataTable(); }
});
For what it's worth, I often have DataTables that are periodically refreshed using ajax. Here is how I instantiate my DataTables in my Ajax success handlers:
success: function (response) {
var $table = $('#user-table');
var $body = $('#user-table-body');
if ($.fn.DataTable.isDataTable($table)) { // if already init, destroy it
$table.dataTable().fnDestroy();
$body.empty(); // empty body of table
}
$body.html(response['users-table']) // set new data to body of table
$table.DataTable({ // init datatable
"order": [
[2, "desc"]
]
});
},

refresh displaytag table using ajax

Hy guys,
I'm trying to solve this problem:
I have a jsp page with inside a table generated with dispaytag library and other kind of stuff.
When I press a button, I would like to generate an ajax call reloading just the table and not the whole jsp page, that display correctly the uptated table with also the generated tag pagebanner and pagelinks properly, increasing and decreasing elements founds.
Is there any solution to solve this problem?
Try this.
$.ajax({
type:"POST",
url:"yourpage.jsp",
data :{ yourdata : yourdata },
success: function(data) {
}
});
$(".yourtableClass").load("yourpage.jsp .yourtableClass", { yourdata : yourdata });

AJAX dropdown within toggle(function) only works once

I have a table where rows are dynamically added.
In one of the cells I would like to toggle between a dropdown and an input box.
The dropdown is a PHP file loaded via AJAX. The issue is the dropdown only renders once.
First time you click the toggle button, the dropdown appears, as it should.
Second click switches it to the input field, as it should.
Third click does nothing, it just stays on the input box and does not toggle back to the dropdown.
If I comment out the AJAX call and put in a simple dropdown, it toggles back and forth just fine. So I believe the issue is with the AJAX portion.
Link to http://jsfiddle.net/6h5BD/1/
NOTE: the AJAX is currently commented out in jsfiddle and replaced with a temp dropdown so you can see what results I am looking for.
The portion of JS in question:
$('input[name="button"]').toggle(function() {
$.ajax({
url: 'http://localhost/brandDropdown.php',
type:'POST',
dataType: 'html',
success: function(output_string){
$('#brand').html(output_string);
}
});
}, function() {
$(this).closest('td').prev().html("<input type=\"text\" name=\"itemBrand[]\" id=\"itemBrand\" size=\"10\" placeholder=\"New Brand\" style=\"text-transform: uppercase\"/>");
});
The PHP:
$sqlbrand = "SELECT BRD_Name FROM Brands ORDER BY BRD_Name asc";
$resultbrand = odbc_exec($conn, $sqlbrand);
ECHO "<select name='itemBrand[]' style='width:120px' size='1'>";
while ($rowbrand = odbc_fetch_array($resultbrand)) {
echo "<option value='".$rowbrand['BRD_Name']."'>".$rowbrand['BRD_Name']."</option>";
}
echo "</select></td>";
I am very open to handling this in a different manner. I have tried several different approaches, but to no avail.
Thank you in advanced for any assistance with this issue.
I cant completely help you debug if I can't see the PHP file.
But from the HTML/JS I can see a potential problem. You are selecting $("#brand") and changing the html to the output_string. But when you are cloning your rows, you are making multiple divs with id of #brand and ids are supposed to be unique, you should use class instead.
Can you try if this works?
$('input[name="button"]').toggle(function() {
var $this = $(this);
$.ajax({
url: 'http://localhost/brandDropdown.php',
type:'POST',
dataType: 'html',
success: function(output_string){
$this.closest('td').prev().html(output_string);
}
});
}, function() {
$(this).closest('td').prev().html("<input type=\"text\" name=\"itemBrand[]\" id=\"itemBrand\" size=\"10\" placeholder=\"New Brand\" style=\"text-transform: uppercase\"/>");
});
In your code (in the fiddle)
$(this).closest('td').prev().html(...)
should be
$(this).closest('td').prev().find('#brand').html(...)
because $(this).closest('td').prev().html(...) is replacing the html of td which means it's just removing the div with id #brand from within the td so in your ajax success callback $('#brand').html(output_string); is not working because it's not inside the td once you toggled it.

Categories

Resources