I have an AJAX call which returns multiple HTML fragments that need replacing on the page:
<div data-replace="some-div">
<p>whatever</p>
</div>
<div data-replace="some-other-div">
<p>something else</p>
</div>
Currently I am adding all the html to a hidden div on the page and then doing:
hiddenDiv.find('[data-replace]').each(function () {
$('#' + $(this).data('replace')).html($(this).html());
$(this).remove();
});
which seems to work but seems a bit hacky.
Is there a better way (whilst still returning HTML rather than JSON as this is out of my control)?
I would create a jQuery object with all DOM elements and not append them to the document as an hidden DIV element since you don't need it. Also you won't need to remove it after your update.
Something like this:
(assuming that your AJAX response is a variable called data)
var $data = $("<div>" + data + "</div>");
$data.find('[data-replace]').each(function () {
$('#' + $(this).data('replace')).html(this.innerHTML);
});
Related
I am pretty new in JQuery and I have the following problem.
I have create this JQuery function that when the user select a file into an input tag having id=rendicontoAllegato it put the name of this file into an hidden div having id=nomeDocumentoRendicontazione into my page
$(document).ready(function() {
$("#rendicontoAllegato").change(function() {
alert("DOCUMENTO dopo selezione: " + $("#nomeDocumentoRendicontazione").text());
var selectedFileName = $("#rendicontoAllegato").val();
$('#nomeDocumentoRendicontazione').append(selectedFileName);
});
});
It works fine but the only problem is that if I first select something asfile1.txt and then select another file as file2.txt into the div having id=nomeDocumentoRendicontazione I will have the concatenation of the 2 files name.
So I will have something like file1.txtfile2.txt and it is not good for me.
How can I replace the value of the div having id=nomeDocumentoRendicontazione instead to append a new value inside it?
You can use the .text() fn if you are dealing with with your data to be inserted as text or .html() fn if you are dealing with html to be replaced
$('#nomeDocumentoRendicontazione').text(selectedFileName);
Or
$('#nomeDocumentoRendicontazione').html(selectedFileName);
Use html() instead of append().
$(document).ready(function() {
$("#rendicontoAllegato").change(function() {
alert("DOCUMENTO dopo selezione: " + $("#nomeDocumentoRendicontazione").text());
var selectedFileName = $("#rendicontoAllegato").val();
$('#nomeDocumentoRendicontazione').html(selectedFileName);
});
});
You have to use
$('#nomeDocumentoRendicontazione').html(selectedFileName);
it will replace the already present HTML of that. OR you can use
$('#nomeDocumentoRendicontazione').text(selectedFileName);
it will do the same but append your data as text.
Sure this is an easy one but finding it hard to search for an answer due to not knowing the exact words to search for :/
also if theres a better way of doing this please do tell me ;)
basically I'm generating some div boxes with various contents and titles
so in my html pages I have:
<div class="itdSec" data-title="What is This">
This is a magical div box with some stuff in it
</div>
in my js file I have
$(".itdSec").prepend("<div class='itdSecTit'>" + this.data("title") + "</div>");
The intent is to add a div to the top of that div with the contents of the data-title arribute
the "this" is causing the errors as this is still the main page. and using $(".itdSec") in its place returns the first one each time.
This works:
$(function(){
$(".itdSec").prepend(function() {
return "<div class='itdSecTit'>" + $(this).data("title") + "</div>";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="itdSec" data-title="What is This">
This is a magical div box with some stuff in it
</div>
alternatively you can do this:
$(function(){
$(".itdSec").each(function() {
$(this).prepend("<div class='itdSecTit'>" + $(this).data("title") + "</div>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="itdSec" data-title="What is This">
This is a magical div box with some stuff in it
</div>
With $('.itdSec') you are selecting all elements with the class .itdSec, however, prepend only works on one element.
What you need to do is use jQuery's .each() to iterate over all the selected elements and prepend the title for every single element.
$('.itdSec').each(function(i) {
// 'i' is the index (0,1,2,3...) - not needed here
// 'this' is now every element in turn
var title = $(this).data('title');
$(this).prepend('<div class="itdSecTit">' + $(this).data("title") + '</div>');
});
(JSFiddle)
Inside the .each() loop you can then use this as the element that is currently being iterated over.
I got this javascript loop which generates a unordered list with maybe 50 list items.. Now I want to put a button in every list item which stores the content in a database. Think retweet.
I figured out a way which is put the button and the content from the listitem within a hidden input in the loop but that seems like a bad shortcut. Like this:
html += "<form action=\"add.php\" method=\"post\"><input type=\"hidden\" value=\"" + listitem + "\" name=\"item\"\/>";
html += "<input type=\"submit\" value=\"repost\" \/><\/form>";
Using jQuery seems much more subtle and more like the right thing to do. I've gotten this far:
$("button").click(function()
var value = ($(this).text());
$.post('add.php',{value:value};
});
With a button in the loop instead of the input. But I can't even get the jQuery to response to the button click. Is there anyway this is possible or should I just go with the shortcut?!
The loop =
var html = "<li><h2 class=\"postTitle\">" + title + " <\/h2>";
html += "<p id=\"postText\" class=\"postText\">" + text + "</p></li>";
$('#Content').append($(html));
And the html where the loop ends up:
<ul id="list">
<div id="Content">
</div>
</ul>
From the code above the jQuery selector being used ("button") will not match anything in your code as you've used an input for the button; try:
$("input[type=submit]").click(function () {
...
});
Ideally use a more targeted selector as I presume you don't want every submit button to do this :)
Try giving your button a unique id?
resulting in:
$('#myId').click(function(){
//your code here
});
That is much better to specify.
You can also try to give it a class and an id
$('.myClass').click(function(){
var myButton = $(this).attr('id');
if(myButton == 'myId'){ do this} else if(myButton == 'myOtherId'){do this}
});
that way you can handle several buttons in one function, and if there are many buttons if statements will make your code look all messed up and you can use a select case :)
First, if you send your data via AJAX $.post, you should prevent submitting a form:
$("button[type=submit]").click(function(oEvent) {
oEvent.preventDefault();
// or in the end of handler
return false;
});
Second, <input> and <button> elements will return nothing in $(elem).text(), to get a value you should use $(elem).val() method.
Third, use the id attribute for HTML elements, this will help you manage DOM easier.
I have a div that I want to write to a popup window (for printing).
I'm grabbing the contents of the div's I want on the page using jQuery's html() function like so:
function printOptions() {
var printwindow = window.open('', 'Report', 'height=600,width=600');
printwindow.document.write('<html><head><title>Report</title>');
printwindow.document.write('</head><body>');
printwindow.document.write($('#ReportHeader').html());
printwindow.document.write($('#ReportData').html());
printwindow.document.write('</body></html>');
printwindow.document.close();
printwindow.print();
return true;
}
However, before I document.write() the contents of the #ReportHeader and #ReportData div's, I would like to alter them a little.
Specifically, I would like to replace all textboxes with a simple span containing that textboxes value.
Something like:
$("input[type=text]").each(function() {
$(this).replaceWith("<span>" + $(this).val() + "</span>");
});
How can I do that to just the contents of those divs without altering my existing page? I just want to modify what I'm going to be writing out to the print window. I don't think I can select on what the html() returns though, because it is just returning a string.
I do ~not~ want to modify the original page that is launching the popup. Just the contents of what I'm going to be writing to the popup.
Any ideas on how I could do this?
You can use .clone() to do it efficiently, like this:
printwindow.document.write(
$('#ReportHeader').clone().find("input[type=text").each(function() {
$(this).replaceWith("<span>" + $(this).val() + "</span>");
}).end().html()
);
This gets a copy of the original #ReportHeader and its children so you can manipulate them how you want without modifying the original, as well as not enduring the expense of html string -> node conversion, which is compartively quite expensive.
You can do whatever you want to the div via the regular jQuery selectors and modifiers.
var $reportHeader = $($('#ReportHeader').html());
// Remove some div
$reportHeader.find('div.to_remove').remove();
// Now use $reportHeader.html() to add the modified contents to printwindow
You can clone the content, then perform the replacements, then write it:
var cloned = $($('#ReportData').html());
Using the $('html string') function:
http://api.jquery.com/jQuery/#jQuery2
To replace all inputs with static span elements, you can do something like this..(not tested)
$(":input").each(function() {
var parent = $(this).parent();
var val = $(this).val();
$(parent).remove($(this).append("<span>" + $(this).val() + "</span>"));
});
i'm a little confused.
i want to actually reload the same page and fetch a div with a certain id from it. so i'm trying to reload a part of website into the same part of the website. ;) i know it sounds weird.
somehow i don't get what i'm doing wrong or better how i have to do it.
var $sv = $('#server_view');
$sv.load('/server/ftp/' + goToURL + " #server_view");
so in this case the same div gets loaded into the same div and that's not what i want.
it then looks like:
<div id="#server_view"> <div id="#server_view"> blabla</div> blabbla </div>
i actually just want to grab the contents of the div inside and reload them. how can i solve this little problem.
You can grab the children with the selector you're passing to .load(), like this:
var $sv = $('#server_view');
$sv.load('/server/ftp/' + goToURL + " #server_view>*");
All we're doing different is getting all direct children to insert using the > child selector.
use .get and replace the element
$.get('/server/ftp/' + goToURL, function(response){
var newContent = $(response).find('#server_view').html();
$('#server_view').replaceWith( newContent );
});
Simple end fast.
$( "#content" ).load( "# #content>*" );
if you are using $('#server_view');, you must have DIV ID as server_view, not #server_view