How can I get the id's of a draggable and droppable element when using jquery UI? - 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;
}
});
});

Related

Trigger change and selection in select2 populated by ajax

I m populating my select2 using ajax with processResults function as in this code,
function PopulateSelect2(sqlclass, ControlID, PlaceHolder) {
$('#' + ControlID).select2({
placeholder: PlaceHolder,
allowClear: true,
theme: "bootstrap",
ajax: {
type: "POST",
url: "../Web_Services/Common/Controllers.asmx/populateCtls",
contentType: "application/json; charset=utf-8",
dataType: "json",
//delay: 250,
data: JSON.stringify({ selector: sqlclass, subselector: '' }),
processResults: function (data) {
var parsed = JSON.parse(data.d);
console.log(parsed)
return {
results: parsed
};
}
},
});}
and I call this function in this way,
$(document).ready(function () {
PopulateSelect2("ddl_occupation", "AddrStateID", "Select")
});
I am trying to set the value after by triggering change but its not working
I tried the following,
$('#AddrStateID').val(4).trigger('change.select2');
I managed to trigger selection inside the list but without showing the value in theselectelement control using this code
$("#AddrStateID").select2("trigger", "select", {
data: { id: "4" }
})
is there a way to trigger the selection and show the result in the select control?
So in i worked around it by pre-populating my select control by ajax call but not by using select2 - ajax call
I added the following attributes to each select control
parent="" param="" child="" placeholder="" aval=""
Where,
parent: represents the parent id selector,
param: represents the control's data parameter that I use for ajax call,
child: represents the control's child control id selector,
placeholder: represents the control's placeholder,
aval: represents the control's assigned value in case wanted to be populated and selected because I use my form for storing data and reading data as well.
in the following example I have 3 select cascade controls.
<div class="panel-body">
<div class="col-xs-12">
<div class="form-grobtn row">
<label class="col-sm-2 col-form-label">File Grobtn</label>
<div class="col-sm-10">
<select id="GpId" style="width: 100%"
class="form-control populate" name="GpId" parent="" param="ddl_btnldgp" child="#CatId"
placeholder="File Grobtn..."
aval="">
<option></option>
</select>
</div>
</div>
<div class="form-grobtn row">
<label class="col-sm-2 col-form-label">File Category</label>
<div class="col-sm-10">
<select id="CatId" style="width: 100%"
class="form-control populate" name="CatId" parent="#GpId" param="ddl_btnldcat"
placeholder="Select File Category..."
child="#CatDtlId" aval="">
<option></option>
</select>
</div>
</div>
<div class="form-grobtn row">
<label for="inputPassword3" class="col-sm-2 col-form-label">File Type</label>
<div class="col-sm-10">
<select id="CatDtlId" style="width: 100%"
class="form-control populate" parent="#CatId" param="ddl_btnldcatdtl" child=""
placeholder="Select File Type..."
aval="">
<option></option>
</select>
</div>
</div>
</div>
</div>
<button id="btn" class="btn cUpldBtn btn-success" type="button">
Assign</button>
And Are being populated using this function
function populateddl(ctl) {
var $this = $(ctl);
var parent, param, child, aval
parent = $this.attr('parent');
placeholder = $this.attr('placeholder');
child = $this.attr('child');
$(child).prop("disabled", true);
param = $this.attr('param');
aval = $this.attr('aval');
if (!parent) {
$.ajax({
type: "POST",
url: "../Web_Services/Common/Controllers.asmx/populateCtls",
data: JSON.stringify(obj = {
selector: param,
subselector: null
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var jsonData = JSON.parse(data.d);
$this.html('').append('<option>')
$(child).prop("disabled", true)
$this.select2({
data: jsonData,
placeholder: $this.attr('PlaceHolder'),
allowClear: true,
theme: "bootstrap"
});
if (aval) { $this.val(aval).trigger('change'); $this.attr('aval',''); }
},
})
}
$this.change(function () {
if ($this.val() && child) {
$.ajax({
type: "POST",
url: "../Web_Services/Common/Controllers.asmx/populateCtls",
data: JSON.stringify(obj = {
selector: $(child).attr('param'),
subselector: $this.val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var jsonData = JSON.parse(data.d);
$(child).html('').append('<option>')
$(child).prop("disabled", false)
$(child).select2({
data: jsonData,
placeholder: $(child).attr('PlaceHolder'),
allowClear: true,
theme: "bootstrap"
});
if ($(child).attr('aval')) { $(child).val($(child).attr('aval')).trigger('change'); $(child).attr('aval', ''); }
},
})
} else {
$(child).html('').append('<option>').prop("disabled", true).trigger('change');
}
})}
Only parents (including childs that are parent to sub select controls) are called using function populateddl(ctl)
in this example I populate as following,
$(document).ready(function () {
populateddl('#GpId');
populateddl('#CatId');
})
In order to assign values, I need to populate and select the value afterwords for child controls,
$(document).ready(function () {
$("#btn").click(function () {
$('#GpId').val(1).attr('aval', '1').trigger('change', 'select2');
$('#CatId').val(2).attr('aval', '2').trigger('change', 'select2');
$('#CatDtlId').val(1).attr('aval', '1').trigger('change', 'select2');
return false;
})
})

Jquery UI selectable: Define multiple selectable objects DYNAMICALLY

I really need some help on the following: I am currently developing a shopping cart. Whenever a new product is appended to shopping cart it becomes a button. This button (product) is used to add some modifiers to each product. The button definition can be seen below:
var productAdded = $('<tr class="product" data-real_id = "'+ id +'" data-id_modal="'+ mod_id +'"><td class="product_name2"><button href="#0" class="button2" style="background-color:#00a65a;" data-comment="" data-modifiers="" data-span_mod = "" data-real_id = "'+ id +'" data-id_modall="'+ mod_id +'" id = "'+ comment_id +'">' + product_name + '</button></td><td class="quantity"><span class="select"><select id="cd-product-'+ id +'" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></span></td><td class="price">' + product_price + '</td><td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td></tr>');
Whenever each of the product's button is pressed a JQUERY UI dialog window is opened whic contains a JQUERY UI SELECTABLE object:
<div class="modal fade" id="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body" style="margin-top:5px;">
<div style="width:100%; float:left;">
<label for="modifier">Τροποποιητές: </label>
<span id="select-result" data-modifiers_span=""></span>
<ol id="selectable" class="txt-modifiers">
<!-- INSERTED BY JQUERY DYNAMICALLY PER PRODUCT -->
</ol>
</div>
<label for="comment">Σχόλιο: </label>
<textarea rows="4" cols="50" name="comment" id="comment" value="" class="form-control txt-comment" style="vertical-align: top;"></textarea>
</div>
<div class="modal-footer" style="margin-top:10px;">
<button class="btn btn-success btn-save" data-id="" data-id_modall="">Αποθήκευση</button>
<button class="btn btn-default" data-dismiss="modal">Κλείσιμο</button>
</div>
</div>
</div>
</div>
As you can see below the modifiers of the product are extracted using AJAZ+PHP from mysql database:
$(document).on('click touchstart','.button2',function(e){
e.preventDefault();
var id = $(this).attr('id'); //Get element id
var real_id = $(this).attr('data-real_id');
var comment = $(this).attr('data-comment'); //Get comment
var modifiers = $(this).attr('data-modifiers'); //Get modifiers
var teeee = $(this).attr('data-id_modall');
$('#modal .txt-comment').val(comment);
$('#modal .btn-save').attr('data-id',id);
$('#modal .btn-save').attr('data-id_modall',teeee);
//alert(modifiers);
if (modifiers.length == 0)
{
$("#selectable").html('<img src="images/ajax-loader.gif" />');
var request = $.ajax({
url: 'http://127.0.0.1:8080/Food%20Ball/backup/FoodBall%20Site%20form_dt_2/Food%20Ball%20Site/get_item_modifiers.php?item_id=' + real_id,
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get',
success: function(data) {
if( data.result != 'Not'){
$("#selectable").html(data.options);
$('#modal .txt-modifiers').val(data.options);
}
else{ $("#selectable").html('Δεν υπάρχουν!');
$('#modal .txt-modifiers').val('Δεν υπάρχουν!'); }
}
});
}
else { $('#modal .txt-modifiers').val(modifiers); $("#selectable").html(modifiers);}
$('#modal').dialog('open');
});
And the selectable object:
$(function () {
$('#selectable').on('touchstart mousedown', function(e) {e.metaKey = true;})
.selectable({
selected: function(event, ui) {
var result = $( "#select-result").empty();
$( ".ui-selected", this ).each(function() {
result.append($(this).attr('data-product_modifier') + ', ');
});
},
unselected: function(event, ui){
var result = $( "#select-result");
$( ".ui-unselected", this ).each(function() {
result.remove($(this).attr('data-product_modifier') + ', ');
});
}
});
});
And finally the "Save" button for each dialog modal window:
$(document).on('click touchstart','.btn-save',function(e){
e.preventDefault();
var id =$(this).attr('data-id'); //Get data id
var comment =$('.txt-comment').val(); //get the comment
var modifiers =$('.txt-modifiers').val(); //get the modifier
//update the "order" note column modal
var note_modal = '#' + $(this).attr('data-id_modall'); //get the id row of the order modal
var note_modal2 = '#2' + $(this).attr('data-id_modall'); //get the id row of the order modal
$(note_modal).find('#note_modal').text(comment+'--'+modifiers);
$(note_modal2).find('#note_modal2').text(comment+'--'+modifiers);
$('#'+id).attr('data-comment',comment);
$('#'+id).attr('data-modifiers',modifiers);
//Save it in data base..s
$('#modal').dialog('close');
$('.txt-comment').val('');//clear text area
$('.txt-modfiers').val('');//clear text area
});
$(document).on('click','.btn-default',function(e){
e.preventDefault();
//Save it in data base..s
$('#modal').dialog('close');
$('.txt-comment').val('');//clear text area
$('.txt-modfiers').val('');//clear text area
});
My problem is that if i add more than one products to my cart the selected modifiers appear for all products. How can i have multiple selectable objects defined dynamically and save each product's selected modifiers?
If anyone can help on this i will really appreciate it
Thank you
ok solved it:
simply put the following code within the successful return of the Ajax call:
var request = $.ajax({
url: 'http://127.0.0.1:8080/Food%20Ball/backup/FoodBall%20Site%20form_dt_2/Food%20Ball%20Site/get_item_modifiers.php?item_id=' + real_id,
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get',
success: function(data) {
if( data.result != 'Not'){
$("#selectable").html(data.options);
$('#modal .txt-modifiers').val(data.options);
$( "#selectable" ).selectable({
stop: function() {
result_mod = $( ".select_result" ).empty();
$( ".ui-selected", this ).each(function() {
result_mod.append(' +' + $(this).attr('data-product_modifier'));
//array_mod = array_mod + (' +' + $(this).attr('data-product_modifier'));
$('#modal .select_result').val(result_mod);
});
}
});
}
else{ $("#selectable").html('Δεν υπάρχουν!');
$('#modal .txt-modifiers').val('Δεν υπάρχουν!');
$( ".select_result").html('');
$('#modal .select_result').val('');
}
}
});

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.

slideToggle and jQuery Ajax - New elements inoperable

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(){...})

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