JQuery draggable and Javascript stop working after ajax call - javascript

I have an on click declared like so:
$('body').on('click', 'input#searchVariables', function () {
var datasetId = $('.TSDatasetID').val();
var term = $('#searchTextbox').val();
alert(term);
$.ajax({
type: "GET",
url: "trendssearchresults.aspx?datasetId=" + datasetId + "&term=" + term,
error: function (xhr, status, error) {
//alert the error if needed
alert('Error: ' + xhr.responseText);
},
success: function (responseData) {
$('#searcharea').html(responseData);
$('#searcharea').show();
}
});
});
It returns the data fine, but my onclick events in that code don't work.
After my ajax inputs the html to my page, none of the javascript works. How do I fix this?
Draggable code:
$(document).ready(function () {
$(".draggableVar").draggable({ revert: false, helper: 'clone', scroll: true, appendTo: 'body', start: function () {
$(this).data("startingScrollTop", $(this).parent().scrollTop());
},
drag: function (event, ui) {
var st = parseInt($(this).data("startingScrollTop"));
ui.position.top -= $(document).scrollTop() - st;
}
});

Try this:
$(document).ready(function () {
//On Dom ready load your draggable if you need to:
loadjs();
$('body').on('click', 'input#searchVariables', function () {
var datasetId = $('.TSDatasetID').val();
var term = $('#searchTextbox').val();
alert(term);
$.ajax({
type: "GET",
url: "trendssearchresults.aspx?datasetId=" + datasetId + "&term=" + term,
error: function (xhr, status, error) {
//alert the error if needed
alert('Error: ' + xhr.responseText);
},
success: function (responseData) {
$('#searcharea').html(responseData);
$('#searcharea').show();
loadjs(responseData);
}
});
});
});
Rebind your draggable :
function loadjs(responseData) {
$(".draggableVar").draggable({ revert: false, helper: 'clone', scroll: true, appendTo: 'body', start: function () {
$(this).data("startingScrollTop", $(this).parent().scrollTop());
},
drag: function (event, ui) {
var st = parseInt($(this).data("startingScrollTop"));
ui.position.top -= $(document).scrollTop() - st;
}
}

You need to rebind your dom elements with $.draggable after appending them to dom. ajax is async and append the elements after your initial draggable call.
function bindDraggables(outer) {
outer.find(".draggableVar").draggable({ revert: false, helper: 'clone', scroll: true, appendTo: 'body', start: function () {
$(this).data("startingScrollTop", $(this).parent().scrollTop());
},
drag: function (event, ui) {
var st = parseInt($(this).data("startingScrollTop"));
ui.position.top -= $(document).scrollTop() - st;
}
});
}
$('body').on('click', 'input#searchVariables', function () {
var datasetId = $('.TSDatasetID').val();
var term = $('#searchTextbox').val();
alert(term);
$.ajax({
type: "GET",
url: "trendssearchresults.aspx?datasetId=" + datasetId + "&term=" + term,
error: function (xhr, status, error) {
//alert the error if needed
alert('Error: ' + xhr.responseText);
},
success: function (responseData) {
var appendableElement = $('#searcharea');
appendableElement.html(responseData);
appendableElement.show();
bindDraggables(appendableElement);
}
});
});

Related

Links are not working in Sortable container (in Android )

In the image below is my sortable container and individual image can be dragged and dropped to sort. But the action links(icons) in the box are not working on the android browser because of the Js. When I remove sortable JS the links work fine. How can I make both of them work together?
Sortable Js
$("#sortable").sortable({
cursor: "move",
start: function (event, ui) {
ui.item.startPos = ui.item.index();
},
stop: function (event, ui) {
var id = ui.item.attr("id");
var PropID = $("#PropID").html();
var obj = {
PropID: PropID,
ID: id,
Pos1: ui.item.startPos ? ui.item.startPos : 0,
Pos2: ui.item.index() ? ui.item.index() : 0
}
try {
$.ajax({
type: "POST",
url: "/members/pm-add-photos.aspx/MovePhoto",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var result = msg.d;
if (result.toLowerCase().indexOf('error') > -1) {
triggertoast("", "We're sorry, there seems to have been an error.", "error");
}
},
error: function (response) {
console.log(response);
},
});
}
catch (err) {
triggertoast("", "We're sorry, there seems to have been an error.", "error");
}
}
});
$("#sortable").disableSelection();

How to get target / class name when draggable stop

I use Jquery UI draggable,
I would like add menu on favorite menu when draggable list menu ...
I using options appendTo, but the problem, how the way menu add to favorite menu when I drag until favorite container...
Sorry for my bad english ...
$("YourSelector").draggable(
{
start: function(event, ui)
{
//This Occurs when drag start
selectedClass = $(this).attr('data-value');
console.log(selectedValue);
},
stop: function() {
//This Occurs when drag stop
selectedClass = $(this).attr('data-value');
console.log(selectedValue);}
});
$(".navbar-menu").draggable({
appendTo: ".navbar-favoritebody ul",
axis: "y",
containment: ".navbar-left",
handle: "a:not([data-disabled]):not([data-type='favorite']):not(:contains('Dashboard'))",
helper: "clone",
start: function(ev, ui) {
$("body").prepend("<div class=\"ondrag\"></div>");
var _this = $(this);
_this.find("a").attr("data-href","favorite/create");
},
drag: function(ev, ui) {},
stop: function(ev, ui) {
$(".ondrag").remove();
var _this = $(this),
desc = parsing.toUpper(_this.find("a").attr("data-slug").replace(/\-/g, " "), 2);
var target = $(event.target);
console.log(target.prop('className'));
if(target.prop("className") == "navbar-favoritebody") {
$.ajax({
type: "POST",
url: location.pathname+"?r="+_this.find("a").attr("data-href"),
data: {
"Favorite[menu_id]": _this.find("a").attr("data-menu"),
},
dataType: "text",
error: function(xhr, errors, message) {
console.log(xhr, errors, message);
},
beforeSend: function() {
navigasi.process("load");
},
success: function(data) {
if(!$.trim(data)) {
notification.open("danger", "Menu "+ desc +" sudah ada di Favorite.", 2000);
} else {
$(".navbar-favoritebody").html(data);
notification.open("success", "Menu "+ desc +" berhasil ditambah ke Favorite.", 2000);
}
},
complete: function() {
navigasi.process("destroy");
_this.find("a").removeAttr("data-href");
}
});
}
},

Jquery UI auto complete (with custom listing) not working

I am trying to use jquery UI autocomplete, but somehow the same won't show up despite having no javascript error.
here is my json data:
{"d":"[{\"label\":\"XYZ\",\"desc\":\"desc 1\",\"value\":\"XYZ\",\"ID\":595,\"icon\":\"UM-892983\"},{\"label\":\"ABC .\",\"desc\":\"desc 2\",\"value\":\"ABC .\",\"ID\":1681,\"icon\":\"UM-432944\"}]"}
Here is my JS Function for processing the autocomplete:
$().ready(function(){
$("#txtName").bind("keyup", function (e) {
// Ajax call returns the above json data
// On Ajax Success I call
onSucName(returnData.d);
});
});
function onSucName(result) {
var varArrAdms = $.parseJSON(result);
$("#txtName").autocomplete({
source : varArrAdms,
select : function (event, ui) {
setNameValue(ui.item.icon)
$("#txtNo").val(ui.item.icon)
$("#btnSearch").click();
},
open : function () {
$(this).addClass('loadingTxtBox');
},
close : function () {
$(this).removeClass('loadingTxtBox');
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.value + " <b> desc:" + item.desc + "</b> <i> No:" + item.icon + "</i></a>").appendTo(ul);
};
}
Where am I wrong?
Try this example
$('#txtName').autocomplete({
source: function (request, response) {
$.ajax({
url: 'url',
data: {}, //pass data here
dataType: 'json',
type: 'post',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.icon
}
}));
}
})
},
select: function (event, ui) {
var itemval = ui.item.label;
// here you can access selected result `itemval`
return false;
},
minLength: 1
});
Why are you binding the autocomplete on keyup.... Rather you should bind it once.
Also, before rebinding it you shoud destroy the existing instance.

jQuery UI .autocomplete()

I have autocomplete working on my site with the following:
$(function () {
$("#client").autocomplete({
source: "/appointments/clients.json",
minLength: 1,
select: function (event, ui) {
$('input[name="clientid"]').val(ui.item.id);
$('#app-submit').html('Add Appointment for ' + ui.item.value);
}
});
});
What I want to do now is that when a user types in something that is not shown on the dropdown, I'd like for the following to take place:
$('input[name="clientid"]').val('');
$('#app-submit').html('Add Appointment');
I tried using the following but it didn't work:
$(function () {
$("#client").autocomplete({
source: "/appointments/clients.json",
minLength: 1,
select: function (event, ui) {
if(typeof(ui.item)){
$('input[name="clientid"]').val(ui.item.id);
$('#app-submit').html('Add Appointment for ' + ui.item.value);
} else {
$('input[name="clientid"]').val('');
$('#app-submit').html('Add Appointment');
}
}
});
});
the select evevnt is only triggered when you select an item in dropdown
you could do it on search event
$(function () {
$("#client").autocomplete({
source: "/appointments/clients.json",
minLength: 1,
select: function (event, ui) {
$('input[name="clientid"]').val(ui.item.id);
$('#app-submit').html('Add Appointment for ' + ui.item.value);
},
search: function() {
$('input[name="clientid"]').val('');
$('#app-submit').html('Add Appointment');
}
});
});
I don't know what the whole idea is without seeing markup. But my guess is:
$("#client").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/appointments/clients.json",
dataType: "jsonp",
success: function( data ) {
var suggestions = $.map( data, function( item ) {
return {
label: item.value,
value: item.id
}
});
// idea: whatever I have, extend to extra item.
suggestions.push({
label: 'Add appointment',
value: 0
});
response( suggestions );
}
});
},
select: function(evt, ui){
if( ui.item.label == 'Add appointment'){
/* do something special with it */
}else{
/* blah blah */
}
}
});

jQuery UI drag and drop problems on IE9

My question is:I does not work drag-an-drop feature of jQuery UI on IE9.What should I do?
Here is my code:
<script type="text/javascript" src="js/jquery-1.3.2-vsdoc.js" ></script>
<script type="text/javascript" src="js/jquery.json-2.2.min.js" ></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js" ></script>
<script type="text/javascript" >
$(function() {
$(".dragbox")
.each(function() {
$(this).hover(function() {
$(this).find("h2").addClass("collapse");
}, function() {
$(this).find("h2").removeClass("collapse");
})
.find("h2").hover(function() {
$(this).find(".configure").css("visibility", "visible");
}, function() {
$(this).find(".configure").css("visibility", "hidden");
})
.click(function() {
$(this).siblings(".dragbox-content").toggle();
updateWidgetData();
})
.end()
.find(".configure").css("visibility", "hidden");
});
$(".column").sortable({
connectWith: ".column",
handle: "h2",
cursor: "move",
placeholder: "placeholder",
forcePlaceholderSize: true,
opacity: 0.4,
start: function(event, ui) {
//Firefox, Safari/Chrome fire click event after drag is complete, fix for that
if ($.browser.mozilla || $.browser.safari)
$(ui.item).find(".dragbox-content").toggle();
},
stop: function(event, ui) {
ui.item.css({ "top": "0", "left": "0" }); //Opera fix
if (!$.browser.mozilla && !$.browser.safari)
updateWidgetData();
}
})
.disableSelection();
});
function updateWidgetData() {
var items = [];
$(".column").each(function() {
var columnId = $(this).attr("id");
$(".dragbox", this).each(function(i) {
var collapsed = 0;
if ($(this).find(".dragbox-content").css("display") == "none")
collapsed = 1;
var item = {
id: $(this).attr("id"),
collapsed: collapsed,
order: i,
column: columnId
};
items.push(item);
});
});
var sortorder = { items: items };
$.ajax({
type: "POST",
url: "not.aspx/siralamakaydet",
data: "{list:'" + $.toJSON(sortorder) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function() {
alert("hata");
},
success: function(msg) {
alert(" Sıralama yapıldı...");
}
});
//Pass sortorder variable to server using ajax to save state
// $.post('updatePanels.php', 'data=' + $.toJSON(sortorder), function(response) {
// if (response == "success")
// $("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000);
// setTimeout(function() {
// $('#console').fadeOut(1000);
// }, 2000);
// });
}
</script>
I think it's your JQuery and JQuery UI version. Check out this related question:
Jquery drag drop bug in IE9
works for that guy in: jquery 1.6.2 & jquery ui 1.8.14

Categories