I have an html table and it's content created with ajax
And I have a button which adds a row at the begining of the table
But JQuery don't know about the ajax content and adds row only after it
$("#add-row-first").on("click", addrowfirst);
function addrowfirst(){
$("#table").prepend("<tr><td>1</td><td>cell</td><td>cell</td><td>cell</td></tr>");
}
ajax
function genTable(){
$.ajax({
type: "POST",
dataType: "html",
url: "inc/gen-table.php",
success: function(data){
$("#table").html(data);
}
});
}
html
<button id="add-row-first">create row</button>
<table id="table"></table>
SOLUTION
So the solution was very simple.
My ajax reqest return string "<tr><td>some text</td></tr>".
So there is no <tbody> tag and the prepend insert code into tbody tag which not exsists.
And it automaticly creates it after ajax generated code. So your ajax should return <tbody><tr><td>some text</td></td></tdbody>
if element #add-row-first is created after the document is created you can't use it that way. You can use the .on() with another parameter so it will find the element like this instead
$("#table").on("click", "#add-row-first",addrowfirst);
If I am understanding your issue correctly, this should do it. The documentation is a little hard to digest, but basically, the first element #table needs to exist at the time of the document being loaded, and the element #add-row-first can be added to the DOM later, as long as it is a child of #table jQuery knows how to find it.
Simplest solution of this case could be
var data = "<tr><td>1</td><td>cell</td><td>cell</td><td>cell</td></tr>";
$('#table').html( data + $('#table').html());
Related
I am using this plugin on my website. You will be able to see the HTML structure it is generating. I am trying to insert custom div after every 5 divs. Since it is loaded asynchronously, I am not able to append div that I wanted. I tried adding the following code which is used in normal situation
$(".alm-reveal:eq(0)").append("<div>Firstdiv</div>");
$(".alm-reveal:eq(1)").append("<div>Second Image</div>");
$(".alm-reveal:eq(2)").append("<div>Third IMage</div>");
$(".alm-reveal:eq(3)").append("<div>Fifth Image</div>");
$(".alm-reveal:eq(4)").append("<div>Sixth Image</div>");
$(".alm-reveal:eq(5)").append("<div>Seventh Image</div>");
$(".alm-reveal:eq(6)").append("<div>Eigth Image</div>");
$(".alm-reveal:eq(7)").append("<div>ninth Image</div>");
which obviously did not work. I also tried adding it in the success function.
success: function (data) {
alm.AjaxLoadMore.success(data);
$(".alm-reveal").append("<div>Firstdiv</div>");
}
But since it is in the loop, it is repeating. I am quite not sure how to achieve this. How do I trigger append function every time an ajax request is made and append different divs I wanted in proper place. Hope I am clear.
success: function (data) {
alm.AjaxLoadMore.success(data);
$(".alm-reveal:last").append("<div>"+data+"</div>"); //selects last div in that class
}
data should be passed accordingly to get different data in the div.
success: function (data) {
alm.AjaxLoadMore.success(data);
$(".alm-reveal:last").append("<div>"+data+"</div>"); //selects last div in that class
}
every time you append, you should append to last div in that particular class
I am answering my own question though I am not sure if this is the efficient way to do. But it works 100% the way I wanted.
if(data.indexOf("aj-l-main-entry-8") > -1) //Making sure AJAX div is loaded
{
if(document.getElementById("element-id") == null) { //Appending div only once
$("#id_of_the_div_you_want_to_append_to").append('<div></div>');
}
}
I have added the above code in the success function.
I was wondering if I could do a javascript appendTo but removing hiding my last tables before the append. Here is the code:
beforeSend: function() {
$("#divAjax").hide();
},
success : function(data){
$("#divAjax").show();
$(data).appendTo("#divAjax");
Can I remove my last table and then appendTo my data?
Just use:
$("#divAjax").html(data);
to overwrite the old content with the new
Yet another "dynamically change select options based on parent option selected" question.
I have the select values changing dynamically - but after my rails render of the child select - I lose the Chosen styling (the jQuery Chosen plugin) and I cannot operate on this newly injected element.
Here is where the code is right now - it's gone through dozens of iterations -
$('#vendor_block').on('change', '#vendor_name', function(){
overlay.show();
var v = $(this).val();
vndr_json = {};
vndr_json["v"] = v;
$.ajax({
type : "GET",
url : "/purchaseorders/upd_vndr_locs",
data : vndr_json,
success: function(res) {
overlay.hide();
// console.log(typeof(res),res);
jQuery("#vndrAddrOpts").html(res);
}
});
$("#vendor_addresses").chosen(); // WHY DON'T YOU RENDER CHOSEN BOX?!
});
I get this new select box on my page - and I want to fire an event when it changes, but the DOM has already loaded, so it doesn't "see" this element I'm guessing.
Also - the Chosen plugin doesn't render on the element. Not sure why - probably the same reason.
I'm using jQuery's .on() like every post on SO says I should. But it doesn't "reload" the elements inside this parent (and 'vendor_block' is the parent div of 'vendor_name' and 'vendor_addresses').
You can see the difference in the select boxes here:
Any help would be great?
UPDATE:
Adding before and after HTML :
<div id="vndrAddrOpts">
<select class="chzn-select vndrLocs span12" id="vendor_addresses" name="vendor_addresses"><option value="">Select Location</option></select>
</div>
That is the raw HTML - but Chosen does the following when the DOM loads:
<div id="vendor_addresses_chzn" class="chzn-container chzn-container-single chzn-with-drop chzn-container-active" style="width: 100%; margin-bottom: 10px;" title=""><span>Select Location</span><div><b></b></div><div class="chzn-drop"><div class="chzn-search"><input type="text" autocomplete="off"></div><ul class="chzn-results"><li id="vendor_addresses_chzn_o_0" class="active-result result-selected highlighted" style="">Select Location</li></ul></div></div>
This is all fine and well - this is what's supposed to happen.
This is the raw HTML after the select box has been injected:
<div id="vndrAddrOpts">
<select class="chzn-select vndrLocs span12" id="vendor_addresses" name="vendor_addresses"><option value="">Select Location</option></select>
</div>
And here is the rendered box - sans Chosen stuff.
<select class="chzn-select vndrLocs span12" id="vendor_addresses" name="vendor_addresses"><option value="">Select Location</option><option value="532757b4963e6505bc000003">Honolulu</option>
<option value="532768d0963e6505bc000004">Waipahu</option></select>
I found the answer here :
Is there a way to dynamically ajax add elements through jquery chosen plugin?
I actually was approaching this problem in an overly complex way - trying to inject and element instead of just starting with the element and adding options to it.
My AJAX looks like this now:
$.ajax({
type : "GET",
url : "/purchaseorders/upd_vndr_locs",
data : vndr_json,
success: function(res) {
overlay.hide();
var va = $('#vendor_addresses');
// console.log(typeof(res),res);
for (var i=0; i < res.length; i++) {
va.append(
$('<option></option>')
.val(res[i].id)
.html(res[i].name)
);
}
va.trigger("liszt:updated");
// jQuery("#vndrAddrOpts").html(res);
}
});
So instead of even worrying about rebuilding the chosen element from an injected element - we just use the built-in "updated" trigger and it works great.
You are inserting the result of your ajax call into the DOM it's success callback, which is executed whenever it finishes (independent of the script's execution). In this case, your ajax request is being made, the code after it begins executing, and then the callback. The odds of the success callback being called before the next line of code are slim, as the ajax call is an http request which takes much longer than a line of JavaScript executing.
You want to put the code in the success call back, such as:
$.ajax({
type : "GET",
url : "/purchaseorders/upd_vndr_locs",
data : vndr_json,
success: function(res) {
overlay.hide();
$("#vndrAddrOpts").html(res);
$("#vendor_addresses").chosen();
}
});
I think the chosen method is firing before the element has actually been rendered on the page, and jQuery can't find it. Try putting $("#vendor_addresses").chosen(); as part of the AJAX success callback. Failing that, try commenting out the chosen() method, running the AJAX script, then manually running the chosen() method. If it works that way, you have to delay it a little bit.
EDIT:
Actually, looking more closely at your code, it appears you're using an ID tag instead of a class. Do multiple HTML elements have the #vendor_address id? If so, use a class instead, and use $('.vendor_addresses').last().chosen();. If you use an ID, and use an ID selector, jQuery will pick the first element if finds with that ID, and stop there.
Lesson to be learned? Use an ID for UNIQUE elements, and classes for multiple elements of the same 'class'.
I'm performing an AJAX request to get a generated html page. I want to find a specific div in the result and inject it into the page where the request came from. I also want to include embedded script or script links which may be inside this div. Here is a simple sample of the page I want to get with AJAX
<html>
<head>
<script>alert("don't want this")</script>
</head>
<body>
<div id='findMe'>
<p>Some content</p>
<script>alert("want only this")</script>
</div>
<script>alert("don't want this")</script>
</body>
</html>
So I only want to extract the div with ID findMe. Here's what I have in the page that's doing the request
<script>
$(document).ready(function(){
$.ajax({
url: "ajax.htm",
success: function(data){
$(data).filter("#findMe").appendTo("#output");
},
dataType: "html"
});
});
</script>
<div id='output'></div>
But the script tag is missing and no alert appears. It seems to get taken out of the div. If I do
console.log($(data))
I can see each of the script tags as a document fragement, but how to I know which one was in the div before it was popped out?
You can try:
$(data).find('#findMe').appendTo('#output');
OR
$('<div/>').append(data).filter("#findMe").appendTo("#output");
Append data to a demo div (not exists in DOM) and make filter over that.
I think instead of .filter(), which filters the current jQuery collection, you have to use .find():
$(data).find("#findMe").appendTo("#output");
But I am unsure whether the script tag will be executed or not..
I had to treat the result as XML. Find the element I'm looking for in the XML object using jQuery .find(), select the actual node (array pos 0), convert the contents of the node to a string, and inject into the output div. This is the only method I've found that executes scripts only contained in the target div.
$.ajax({
url: "ajax.htm",
success: function (data){
var node = $(data).find("#findMe")[0];
if(node.xml)
{
$("#output").html(node.xml)
}
else if(new XMLSerializer())
{
$("#output").html((new XMLSerializer()).serializeToString(node));
}
},
dataType: "xml"
});
My question is very similar to this topic. I'm trying to use jquery, so that when you click on a table row, it loads certain information from another page and insert as a new row below the one clicked on.
If I didn't have to load the data from another page, I could just use something like:
clicked.after('<tr><td>Something</td><td>Something</td></tr>');
If I wanted to load and insert into something other than a table, I could use something like:
clicked.after($('<div>').load("Page2.aspx"));
So how do I go about combining these two together? If I have on the first page:
clicked.after($('<div>').load("Page2.aspx"));
And have Page2.aspx returning:
<tr><td>Something</td><td>Something</td></tr>
I would get this:
<tr><td>...</td><td>...</td></tr><div><tr><td>Something</td><td>Something</td></tr></div>
Which is not valid HTML.
Any suggestions?
Use after in the callback of a get rather than load.
$('.clicked').click( function() {
var $clicked = $(this);
$.get('Page2.aspx', function(html) {
$clicked.after(html);
});
});