JQuery replace entire DIV using .load() - javascript

I want to refresh a <div> on the close of a jQuery UI Modal Dialog.
My code is:
var dialog = jQuery('#divPopup').dialog({
autoOpen: false,
height: 450,
width: 650,
modal: true,
open: function(event, ui) {
jQuery('body').css('overflow', 'hidden');
},
close: function(event, ui) {
jQuery('#divPopup').dialog('destroy').remove();
jQuery("#bodyId").load("http://www.xyz.com/ #bodyId");
}
});
But instead of replacing it, that adds the new <div> inside the old <div>:
<div id="bodyId">
<div id="bodyId">
New Response
</div>
</div>
I want to replace old div bodyId with new div bodyId.

Try to replace this:
jQuery("#bodyId").load("http://www.xyz.com/ #bodyId");
... with this:
jQuery("#bodyId").load("http://www.xyz.com/ #bodyId > *");
This works because you can use any selector after the URL. By using #bodyId > * instead of just #bodyId, you match everything that is inside the div, instead of the div itself.
You need this because .load() will not replace an element; it will append the result of the AJAX call to the element.
Alternatively, you could use .get() to load the data and manually perform the selection, like so:
$.get('http://www.xyz.com/', function(data) {
var newContent = $(data).find('#bodyId').children();
$('#bodyId').empty().append(newContent);
});
Examples of both methods are online here: http://jsfiddle.net/PPvG/47qz3/

You could also use jquery.get.
$.get('http://www.xyz.com/', function(data) {
$('#bodyId').html(data);
});

you may be use this code like
$('#bodyID').remove();
$('#bodyID').load();

Related

JQuery closest() + find() tree traversal

Given a structure like this:
<div class="portlet">
<div class="portlet-config">
<p>Some configuration</p>
</div>
<div class="portlet-header">Configurable portlet</div>
<div class="portlet-content">This has a configuration window. Click on pencil icon to open.</div>
</div>
First, I append these DIVs to portlet-header (to display some buttons)
<div class="portlet-button-container">
<div class="portlet-button portlet-btn-delete ui-icon ui-icon-close"></div>
<div class="portlet-button portlet-btn-toggle ui-icon ui-icon-minusthick"></div>
<div class="portlet-button portlet-btn-config ui-icon ui-icon-pencil"></div>
</div>
Then I apply a jquery-ui dialog() plugin to the portlet-config DIVs
$(".portlet-config").dialog({
autoOpen: false,
show: {
effect: "fade",
duration: 200
},
hide: {
effect: "fade",
duration: 500
},
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
Then I add come click handlers
$(".portlet-btn-toggle").click(function () {
var icon = $(this);
icon.toggleClass("ui-icon-minusthick ui-icon-plusthick");
icon.closest(".portlet").find(".portlet-content").toggle();
});
$(".portlet-btn-delete").click(function () {
var icon = $(this);
icon.closest(".portlet").hide();
});
$(".portlet-btn-config").click(function () {
var icon = $(this);
icon.closest(".portlet").find(".portlet-config").dialog("open");
});
It seems that the portlet-config DIV could not be found when the user clicks on the pencil.
More precisely it seems that:
$(this) // OK, returns an object
$(this).closest(".portlet") // OK, returns an object
$(this).closest(".portlet").find(".portlet-config") // NOK, returns null
Here is a fiddle to reproduce the problem: http://jsfiddle.net/silenzioso/M6LmS/
Thanks in advance
Your call to $(".portlet-config").dialog is doing a little more than you expect it to. If you look in the DOM, you can see that the div has been moved out of its original location and added to the end of the document. Presumably it does this for the overlayed dialog effect.
You could consider putting a unique ID on the dialog div so that you can find it again. Perhaps you could use a data attribute to store the associated dialog div ID in the button.
<div class="portlet">
<div class="portlet-config" id="dialog1">
<p>Some configuration</p>
</div>
<div class='portlet-button' data-config="dialog1"></div>
</div>
...
var id = $(this).data('config');
var config = $('#'+id);
If You are dynamically creating new DOM elements in jQuery make sure You add event click on body or document or other element that is defined from the very first page display (I mean server response):
$('body').on('click', '.portlet-btn-config', function(e){
});

Refresh child in dynamically created nested accordion

I am trying to append items to a nested accordion dynamically when the user clicks a button. I am using the following code to create a nested accordion:
$(".accordion").accordion({
collapsible: true,
autoHeight: false,
animated: 'swing',
heightStyle: "content",
changestart: function(event, ui) {
child.accordion("activate", false);
}
});
var child = $(".child-accordion").accordion({
active:false,
collapsible: true,
autoHeight: false,
animated: 'swing'
});
In order to do this, I have found that I need to refresh the accordion using the following:
$('.accordion').accordion("refresh");
My problem is that when I try to refresh the inner accordion using:
$('.child-accordion').accordion("refresh");
I get the following:
Error: cannot call methods on accordion prior to initialization; attempted to call method 'refresh'
When I inspect the div that should be refreshed it has the following ids/classes:
DIV#shelf0sections.child-accordion.ui-accordion-content.ui-helper-reset.ui-...
I tried using the selector:
$('#shelf0sections .child-accordion').accordion("refresh");
instead which doesn't give an error, but nothing happens visually.
jsFiddle: http://jsfiddle.net/Mw9SA/3/
(Note that the first element in the list is just an example to see the nested accordion working, If you try to add sections to it, it won't work. Use the '+Shelf' button, then open the new accordion and use the '+Section' button.)
How about a more modular approach?
Fiddle or it didnt happen: http://jsfiddle.net/Varinder/24hsd/1/
Explanation
The idea is ( the same ) to create a brand new accordion element on the fly with correct events attached and appended somewhere in the DOM.
It's generaly more managable to have repeater HTML markup abstracted away in a template somewhere in DOM and use JS to reference it rather that building it from a string.
Heres the accordion template in the markup:
<div class="template">
<div class="accordion">
<h3 class="accordion-title">accordion title</h3>
<div class="accordion-content">
accordion content
</div>
</div>
</div>
Heres the full HTML markup - just in case:
<div class="page">
</div>
<div id="addShelf" class="button">+ Shelf</div>
<div id="addSection" class="button">+ Section</div>
<div class="template">
<div class="accordion">
<h3 class="accordion-title">accordion title</h3>
<div class="accordion-content">
accordion content
</div>
</div>
</div>
JS
Starting off by storing different accordion configurations:
var shelfConfig = {
collapsible: true,
autoHeight: false,
animated: "swing",
heightStyle: "content"
}
var shelfSectionConfig = {
active:false,
collapsible: true,
autoHeight: false,
animated: "swing"
}
Kepping a track of current accordion number and current accordion section number ( number of sections inside last accordion ) - might come in handy if you require a feature to remove an accordion shelf
var currentShelfNumber = 0;
var currentShelfSectionNumber = 0;
Chaching DOM elements, notice reference to the tempalte div
var $page = $(".page");
var $accordionTemplate = $(".template").children();
var $addSection = $("#addSection");
var $addShelf = $("#addShelf");
Creating a helper function that simply returns a cloned copy of the accordion template from the DOM
function getAccordionTemplate() {
return $accordionTemplate.clone();
}
Main function generateAccordion - it takes two arguments, accordionNumber to append current number in titles etc and accordionType to find out which accordion configuration to use.
With those parameters it will return a brand-spanking-new accordion with appropriate events attached which can then be append to the DOM
function generateAccordion( number, accordionType ) {
var $accordion = getAccordionTemplate();
var accordionTitle = "twerking bieber?";
if ( accordionType == "shelf" ) {
accordionTitle = "Shelf " + number;
} else {
accordionTitle = "Shelf Section";
}
$accordion.find("h3").text( accordionTitle );
var $accordionWithEvents = attachAccordionEvents( $accordion, accordionType );
return $accordionWithEvents;
}
Notice the call to another function attachAccordionEvents as the name suggests - this fella will attach events to the accordion element.
function attachAccordionEvents( $accordionElement, accordionType ) {
if ( accordionType == "shelf" ) {
$accordionElement.accordion( shelfConfig );
} else {
$accordionElement.accordion( shelfSectionConfig );
}
return $accordionElement;
}
Another helper function which makes sure "add section" button doesnt show up if there is no accordion shelf for it to work on
function manageSectionButton() {
if ( $page.children().length > 0 ) {
$addSection.show();
} else {
$addSection.hide();
}
}
Finaly events and logic:
$addShelf.on("click", function(e) {
e.preventDefault();
var newShelfNumber = currentShelfNumber + 1;
var $shelfElement = generateAccordion( newShelfNumber, "shelf" );
currentShelfNumber = newShelfNumber;
$page.append( $shelfElement );
manageSectionButton();
});
$addSection.on("click", function(e) {
e.preventDefault();
var newShelfSectionNumber = currentShelfSectionNumber + 1;
var $shelfSectionElement = generateAccordion( newShelfSectionNumber, "section" );
var $activeShelfElement = $page.children().last().find(".accordion-content");
$activeShelfElement.append( $shelfSectionElement );
});
... And thats about it.
Hope this helps,
Cheers

How to set position for dialog created via JavaScript

HTML:
Link
JavaScript
$(document).ready(function() {
$(document.body).on('click',"a",function(event){
if ($(this).hasClass('ui-dialog-titlebar-close')) return;
event.preventDefault();
var data = '<div id="dialog" title="Basic dialog">';
data += '<p>Hello.</p></div>';
$(data).dialog();
});
});
I want to set a position for this dialog. I've tried changing $(data).dialog(); to $(data).dialog('option', 'position', [200,300]);, but it doesn't work. How can I set it?
jsFiddle: http://jsfiddle.net/fcTcf/
it should be:
$(data).dialog({
position: [200, 300]
});
The syntax $(data).dialog('option', 'option-name', value) is used for changing an option of a dialog that has already been initialized. But if you want to specify options at initialization time, you do so using a option object as the argument to the widget.
There is a link to api documentation for the jQuery Dialog Widget and this jQuery position will help you if you want more granular control of the position.
You're using the selector incorrectly.
$(data) where $data is not a class or id, data is a string containing html.
Try $("#dialog").dialog(); And then you surely would be able to figure it out with the API-documentation.
$(document).ready(function() {
$(document.body).on('click',"a",function(event){
if ($(this).hasClass('ui-dialog-titlebar-close')) return;
event.preventDefault();
var data = '<div id="dialog" title="Basic dialog">';
data += '<p>Hello.</p></div>';
var options={
position:[200,300]
};
$(data).dialog(options);
});
});
You can set 'option' like this

execCommand insertHtml, outer div not inserted why?

Why is the DIV not inserted but only the IMG ?
$(document).ready(function() {
$(document).on('click', '#insertImage', function(){
/*
Why is the DIV not inserted ?
*/
var item = "<div class='resizable'><img src='http://www.rockiesventureclub.org/wp-content/uploads/2013/02/flower-icon.png'></div>";
document.execCommand('insertHTML', false,item);
})
});
see:
http://jsfiddle.net/daslicht/gU2jP/#base
Why not doing it with jQuery since you already use it??
http://jsfiddle.net/gU2jP/5/
var _$div = $('<div>'),
_$img = $("<img class='resizeable' id='myImg' src='http://imperavi.com/img/library.jpg' />");
_$div.append(_$img);
$('body').append(_$div);
The background of the Question was the following:
I just like to be able to make the added Image Float Left or Right.
Since jQueryUI automatically adds a wrapper-div around each resizeable item I thought that I need to add it somehow manually in order to assign a id to it.
doug65536 on Freenode helped me to create this solution without the need to create an additionally div manually:
We also discovered that the Fiddle wont work properly in safari
$(document).on('click', '#insertImage', function () {
document.execCommand('insertHTML', false,
"<img class='resizeable' id='myImg' src='http://imperavi.com/img/library.jpg'>");
$(".resizeable").resizable({
aspectRatio: true
}); //just a try here
$('#myImg').parent().css({
'float':'left',
'margin':'15px'
});
})
http://jsfiddle.net/daslicht/6cGbQ/
Thank you very Much !

Using jQuery replaceWith on html elements

I'm writing an MVC application and on one page I need to dynamically give an ID to all the elements because of the way the table is rendered and how data is passed to an from it. When I run this, all the elements are replaced with , however it is removing the content in between the tags. Is there any way to make it only replace the starting tag and not touch the rest, or another jQuery function to do this? My code is below:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
var oTable1 = $('#example1').dataTable({
sScrollX: "100%",
sScrollY: "200px",
bFilter: false,
bScrollCollapse: true,
bPaginate: false,
bScrollInfinite: true,
iScollLoadGap: 10,
oLanguage: {
sZeroRecords: "There are no records that match your search criterion",
}
}).makeEditable({ sUpdateURL: "/Home/UpdateData" });
});
</script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function () { var editChange = $('td').replaceWith('<td id = "#Html.ValueFor(x => x.name)" >'); });
</script>
Any help is appreciated.
Instead of using replaceWith may I suggest the use of another function, the function .attr() that is meant to replaced the attributes of an element.
$('td').attr('id','#Html.ValueFor(x => x.name)');
Also, be careful because the ASP values will not be available once in the client side. Your selector $('td') is pretty general, and IDS must be unique.
Try explicitly setting the id on the TD element(s)
$('td').each(function() {
this.id = #Html.ValueFor(x => x.name);
});

Categories

Resources