slideToggle and jQuery Ajax - New elements inoperable - jquery-ui

When I introduce new elements to my slideToggle they look fine and are active (expanded by default) however if I click a pre-existing element all elements collapse and I cannot expand the new ajax elements. Essentially the new ajax elements are not part of the slideToggle group because that was constructed before the elements were introduced. How do I rebuild the toggle on the fly or make the new elements behave as expected?
** jQUERY
$('div.menu_body:eq(0)').show();
$('.acc .head:eq(0)').show().css({color:"#2B6893"});
$(".acc .head").click(function() {
$(this).css({color:"#2B6893"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
$(this).siblings().css({color:"#404040"});
});
** Ajax
<script type="text/javascript">
jQuery(document).ready(function() {
setInterval("showNewFeeds()", 10000);
});
showNewFeeds() {
$.ajax({
type: 'POST',
url: 'feed.php',
data : {uid : '145', mid: '22', nid: 56'},
success: function(response) {
$('#feedNote').html(response).fadeIn('slow');
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.status);
//alert(thrownError);
}
});
}
</script>";
** HTML
<div class="widget acc" id="feedNote">
<div class="head"><h5>Header 1</h5></div>
<div class="menu_body">
<div>HTML 1</div>
</div>
<div class="head"><h5>Header 2</h5></div>
<div class="menu_body">
<div>HTML 2</div>
</div>
</div>

Try :
$(document).on('click', '.acc .head', function() {
$(this).css({color:"#2B6893"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
$(this).siblings().css({color:"#404040"});
});
instead of .click(function(){...})

Related

Jquery Sortable and Dragable - Replace dragged content with Ajax result

This is probably a simple question, but how can I replace the thing I am dragging with html from an ajax call?
So, if the draggable items are just 'text' items (as below in the html snippet), and when I drag the thing I use a 'image' via the helper method, how can I 'on drop' not use either of them but insert the html as returned from a ajax call.
Where do I make the call (btw, using the 'input-type' value to the ajax call to get the correct html)?
How to I prevent the default 'dragged item' from being inserted? I.e. I don't want the div put in or the helper method image....
Do I need to add like a droppable or do I do this in the sortable on like the received event (kind of works, can't remove image but from help method)??? (I have been trying both, and whilst the ajax call worked and I get the data etc, given that I don't know how to prevent the default stuff being dropped I am not sure 'what' I am replacing with the 'result' from the call...)
$("#desktoplayout").sortable({
receive: function (event, ui) {
$(this).append('<div>html from ajax call</div>'); // kind of works... but the image from the 'helper method' on the 'draggable' is still there.
}
}); // A sortable list of stuff into which things are dragged.
var input-type;
$("#draggableItems .item").draggable({
connectToSortable: "#desktoplayout",
helper: function (event) {
return "<div class='item'><img src='/Images/Header.png' /></div>";
},
start: function (event, ui) {
input-type = $(this).find('.preview').data("input-type");
},
drag: function(e, t) {
},
stop: function(e, t) {
}
});
and
<div id="draggableItems">
<div class="item">
<div class="preview" data-input-type="1">
TEXT
</div>
</div>
</div>
Update
This seems to do what I wanted... is calling remove on the helper the correct way of doing this?
receive: function(event, ui) {
ui.helper.remove();
var $this = $(this);
$.get("somewhere", function(data) {
// Note: presume more logic here.....
$($this).append(data);
});
}
Here is a working example of one solution:
https://jsfiddle.net/Twisty/zh9szubf/
HTML
<div id="draggableItems">
<div class="item">
<div class="preview" data-input-type="1">
TEXT
</div>
</div>
</div>
<ul id="desktoplayout">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
JQuery
$(function() {
$("#desktoplayout").sortable({
receive: function(event, ui) {
var newItem;
$.post("/echo/html/", {
html: "<li class='newItem'>From Ajax</li>"
}, function(data) {
ui.helper.replaceWith(data);
});
}
});
var inputType;
$("#draggableItems .item").draggable({
connectToSortable: "#desktoplayout",
helper: function (event) {
return "<div class='item'><img src='/Images/Header.png' /></div>";
},
start: function(event, ui) {
inputType = ui.helper.find('.preview').data("input-type");
}
});
});
This will work with $.get() too, but for the example, it had to be $.post(). Basically, whatever you want top be the result, That code should be in the ui.helper.replaceWith() section.

How can I get the id's of a draggable and droppable element when using jquery UI?

I am trying to use the code below to trigger an ajax request when I drop a dragged element, but it doesn't work. I think it's because I'm not actually getting the id's, but I'm not sure.
HTML:
<div class="draggable">item 1</div>
<div class="draggable">item 2</div>
...
<div class="droppable">drop location 1</div>
<div class="droppable">drop location 2</div>
...
jQuery:
$(document).ready(function() {
$(".draggable").draggable({cursor: 'move', helper: 'clone'});
var ID1 = $(".draggable").attr(id);
var ID2 = $(".droppable").attr(id);
$(".droppable").droppable({
drop: function() {
$.ajax({
type: "POST",
url: 'www.mydomain.com/'+ID1+'/'+ID2,
dataType: 'html',
success: function(){}
});
return false;
}
});
});
ajon's answer is not quite right - both ID1 and ID2 relate to the target (where the dragged element has been dropped), whereas the question asks for id's of both dragged and dropped elements.
given modified html of (as per question but with added id's for all elements)
<div class="draggable" id="item1">item 1</div>
<div class="draggable" id="item2">item 2</div>
...
<div class="droppable" id="drop1">drop location 1</div>
<div class="droppable" id="drop2">drop location 2</div>
...
this javascript should work:
$(document).ready(function() {
$(".draggable").draggable({cursor: 'move', helper: 'clone'});
$(".droppable").droppable({
drop: function(event, ui) {
var dragID = ui.draggable.attr('id');
var dropID = event.target.id; // or $(this).attr("id"), or this.id
$.ajax({
type: "POST",
url: 'www.mydomain.com/'+dragID+'/'+dropID,
dataType: 'html',
success: function(){}
});
return false;
}
});
});
ps - you are also doing an ajax POST but with no posted data - I assume that was removed from the question. If you are just hitting the url and passing the 2 id's as shown then a straight GET would suffice.
$.get('www.mydomain.com/'+dragID+'/'+dropID, function(data) {
..
});
The way you are trying to get the id is invalid. You are using the class selector . which will return all objects of the given class. In your example you have 2+ of each class (draggable and droppable).
Secondly, those elements don't have ids so .attr(id) would return null (I think).
Third, you don't have quotes around id which means it would be interpreted as a variable which hasn't been set.
Lastly, to get the id, you can get it using event.target.id in the drop function.
Try the following:
<div class="draggable" id="item1">item 1</div>
<div class="draggable" id="item2">item 2</div>
...
<div class="droppable" id="drop1">drop location 1</div>
<div class="droppable" id="drop2">drop location 2</div>
...
Then:
$(document).ready(function() {
$(".draggable").draggable({cursor: 'move', helper: 'clone'});
$(".droppable").droppable({
drop: function(event, ui) {
var ID1 = event.target.id;
var ID2 = $(this).attr("id");
$.ajax({
type: "POST",
url: 'www.mydomain.com/'+ID1+'/'+ID2,
dataType: 'html',
success: function(){}
});
return false;
}
});
});

asp.net mvc + knockout + ajax partial load + reuse viewodel and load different data within the same page

In a single asp.net MVC page, I've to show 3 reports of same layout/structor. So I created a page that generated a report using Knockout databind and 10 reports are generated by passing some additional parameters.
I tried to load all 3 reports using Ajax partial view and by this way I'm populating those 10 reports in one single page.
Now I happen to see a strange issue, the last report data appears for all the 3 reports though the data for each report is different. Anyone knows how to handle this issue ?
Main Page View, where I call 3 reports via Ajax call.
<div id="RecentlyAddedReport" ></div>
<div id="RecentlyConsultedReport"></div>
<div id="RecentlyPrescribedReport"></div>
<!-- start here -->
<script type="text/javascript">
$(document).ready(function () {
AjaxLoadReport('RecentlyAddedReport', 'Patient/Report?type=RecentlyAdded&name=Recently Added');
AjaxLoadReport('RecentlyConsultedReport', 'Patient/Report?type=RecentlyConsulted&name=Recently Consulted');
AjaxLoadReport('RecentlyPrescribedReport', 'Patient/Report?type=RecentlyPrescribed&name=Recently Prescribed');
});
function AjaxLoadReport(reportType, actionURL) {
var resultDiv = $('#' + reportType);
$.ajax({ type: "GET", url: actionURL, data: {},
success: function (response) {
resultDiv.html('');
resultDiv.html(response);
}
});
}
</script>
Report View - I call this same view for all the 3 reports
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<TryHomeo.Web.UI.Models.UserControlViewData>" %>
<script type="text/javascript" src="../../scripts/jquery-1.7.1.min.js"></script>
<script src="../../Scripts/jquery.timeago.js" type="text/javascript"> </script>
<script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"> </script>
<h1>
<%:Model.ReportName%>
</h1>
<div class='loadingIndicator' title="Loading..."></div>
<ul id="<%=Model.ReportType %>" data-bind="template: { name: 'patient-template', foreach: patients}"></ul>
<script type="text/html" id="patient-template">
<span>
<li>
<div>
<a data-bind="text: PatientName"></a>- (<abbr class='timeago' data-bind="timeago: DatedString"></abbr>)
</div>
</li>
</span>
</script>
<script type="text/javascript">
// ReportViewModel View Model //
function ReportViewModel() {
var self = this;
self.patients = ko.observableArray([]);
}
var objVM = new ReportViewModel();
ko.applyBindings(objVM);
// Using jQuery for Ajax loading indicator
$(".loadingIndicator").ajaxStart(function () { $(this).fadeIn(); }).ajaxComplete(function () { $(this).fadeOut(); });
$(document).ready(function () {
$.ajax({
dataType: 'json',
url: '/Patient/GetPatientReport/?type=' + '<%=Model.ReportType %>' + '&' + '<%=DateTime.Now.ToString() %>',
success: SetData,
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
});
function SetData(data) {
objVM.patients(data);
}
ko.bindingHandlers.timeago = {
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var $this = $(element);
// Set the title attribute to the new value = timestamp
$this.attr('title', value);
// If timeago has already been applied to this node, don't reapply it -
// since timeago isn't really flexible (it doesn't provide a public
// remove() or refresh() method) we need to do everything by ourselves.
if ($this.data('timeago')) {
var datetime = $.timeago.datetime($this);
var distance = (new Date().getTime() - datetime.getTime());
var inWords = $.timeago.inWords(distance);
// Update cache and displayed text..
$this.data('timeago', { 'datetime': datetime });
$this.text(inWords);
} else {
// timeago hasn't been applied to this node -> we do that now!
$this.timeago();
}
}
};
</script>

Issue when submitting form data via JQuery UI Dialog to the server

I have an asp.net mvc app, using JQuery UI dialog. I'm trying to submit form data to the controler action method. I do hit the action method but my object has no data. Do you know why?
From Filter.cshtml
$("#selectUnits").dialog({
autoOpen: false,
title: 'Select Units',
width: 400,
modal: true,
minHeight: 200,
buttons: {
"Cancel": function () {
$(this).dialog("close");
},
"Submit": function () {
$.post('/Data/SetUnitNumbers', $("#frmSelectedUnits").submit(), function (data) {
alert('This worked');
});
}
} // END OF BUTTONS
}); //END OF DIALOG
From Controler...Action Method:
public void SetUnitNumbers(object data)
{
int a = 5;
}
From SelectUnits.cshtml where form 'frmSelectedUnits' lives. Essentially it is a bunch of checkboxes values that I'm trying to send back to the server:
<body>
<form id="frmSelectedUnits" action="/" >
<div id="unitNumberCheckboxes" style=" ">
<div>
#Html.CheckBox("SelectAllUnitNumbers", false)<label for="SelectAllUnitNumbers"><b>Select/Unselect All Units</b></label>
</div>
<div id="unitCheckboxes">
#foreach (var item in Model)
{
<div style="float:left">
#Html.CheckBox("UnitNumbers", false)<label for="UnitNumbers">#item.unit_number.ToString().PadLeft(3, '0') </label>
</div>
}
</div>
</div>
</form>
</body>
jQuery .post is:
$.post(url, data, success-callback-function);
where data is A map or string that is sent to the server with the request.
Calling $("#frmSelectedUnits").submit() probably won't work.
Try:
$.post('/Data/SetUnitNumbers', $("#frmSelectedUnits").serialize(), function (data) {
alert('This worked');
});
jQuery docs on .serialize()

submit form after clicking selected tab and page also stay on that tab

I would like to do the following:
1. tab-1 is selected when page load at first time
2. After clicking tab-2, form is submitted and page need to stay on the tab-2
I have tested two code snippets. However, both of them have errors (see at below):
<form id="target">
<ul>
<li>Tab-1</li>
<li>Tab-2</li>
<li>Tab-3</li>
</ul>
<div id="tabs-1">
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
</form>
code 1-
It works with point2 and doesn't work with point 1
<script>
$(function() {
var $tabs = $('#tabs').tabs();
$tabs.tabs( "option", "selected", 1 );
$('#tabs-B').click(function() {
$('#target').submit();
});
});
</script>
code 2-
It works with point1, but form doesn't submit after clicking tab-2
var $tabs = $('#tabs').tabs();
$('#tabs-B').click(function() {
$('#target').submit(function() {
$tabs.tabs( "option", "selected", 1 );
});
});
use the [select][1] method
$( "#tabs" ).tabs({
select: function(event, ui) {
var data = $("#from1").serialize();
console.log(data);
// submit the for via ajax here
/*$.post("/path",{data:data},function(){
//clear the form fields or what ever you want to do
});*/
}
});
http://jsfiddle.net/5RMxZ/16/

Resources