Update z-index on image using AJAX - javascript

I have this JQuery UI sortable list that has draggable elements and when I drag it from the bottom to the top, it saves a value corresponding to it's place in the list and saves it in the database. This works! But I need an image on my webpage to update simultaneously by chaning it's z-index. So once a item from the list has been moved to another place in the list, the z index gets stored in the database (which works) and then I need it to change the specific image to using that same z-index. My AJAX code looks like this:
$(document).ready(function () {
$("#sortable").sortable({
axis: "y",
stop: function (event, ui) {
var data = $(this).sortable("serialize");
//These next 2 lines are just a poor attempt to achieve what I want:
var change_zindex = 1;
document.getElementsByClassName('item2')[0].setAttribute("alt", change_zindex);
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: "POST",
url: "database/update_settings_sort.php"
});
}
});
$( "#sortable" ).disableSelection();
});
Well I hope you have some suggestions or advice. Thanks in advance, please tell me if you want me to provide more code.
Edit:
This is what I have now:
var change_zindex = 1;
document.getElementsByClassName('item2')[0].setAttribute("alt", change_zindex);
Only problem is to
1. Know what the change_zindex variable shall be equal to.
2. Be able to do it with all items on the list and not just only item2. I could use something like 'item' + img_id but I don't know how to retrieve that id. Hmm Thanks all

Your code works fine but make sure you are getting the value for variable 'img_id' in the following three lines
var zindex = document.getElementsByClassName('item' + img_id)[0].getAttribute('z-index');
var change_zindex = 1;
document.getElementsByClassName('item' + img_id)[0].setAttribute("z-index", change_zindex);

Related

Problem selecting an item after building the select options with AJAX

I use this javascript to select a specific option (the option value being specified within a hidden element):
$("select").each(function() {
var id = $(this).attr('id');
var source = 'input:hidden[name=select_'+id+']';
if ($(source).length) {
var selected = $(source).val();
$(this).val(selected).change();
}
});
This works fine when the options are hard coded in the HTML source.
I now need to populate the options with an AJAX call, I use the below method:
select : function(ctrl,id) {
var call = '/'+ctrl+'/'+$("#auth input[name=verify]").val();
$.getJSON(call, function(result) {
$.each(result, function() {
$('#'+id).append($("<option />").val(this.id).text(this.title));
});
});
},
I process the select method (AJAX) on page load, and the options populate fine. But when I then try to select the desired option, the browser defaults to the first option.
I have tested what is happening by sticking some alerts around the code as thus:
alert($(this).val(selected)); // A
alert($(this).val()); // B
$(this).val(selected).change();
alert($(this).val()); // C
When the options are hard coded I get A=3, B=null, C=3 i.e. it works
When the options are populated via AJAX I get A=3, B=null, C=null i.e. it fails
I am guessing that I need to trigger some kind of change() event after populating the option list with AJAX. I have tried (a bit overkill I know):
$('#'+id).append($("<option />").val(this.id).text(this.title).change());
&
$('#'+id).append($("<option />").val(this.id).text(this.title)).change();
Any ideas? Thx
Problem solved.
Although I was triggering the code in the correct order (in theory), because of javascripts event driven behaviour the AJAX call was not completing until after my select initialisation had finished. So I moved the code to set the selected option into the AJAX call and voila.
select : function(ctrl,id) {
var call = '/'+ctrl+'/'+$("#auth input[name=verify]").val();
$.getJSON(call, function(result) {
$.each(result, function() {
$('#'+id).append($("<option />").val(this.id).text(this.title));
});
var source = 'input:hidden[name=select_'+id+']';
if ($(source).length) {
var selected = $(source).val();
$('#'+id).val(selected).change();
}
});

Trying to use an id from the same page that my .click function was triggered on, in an ajax function

newbie to coldfusion/jquery/programming general here. So the overview of my problem is this: I have a ticket id that corresponds with a specific row in my database. When I click a button, I would like one of the columns in that row to change values to "In Testing". My issue is that I do not know how to pull that ticket id number into my jquery function, or if this is even possible. My code:
<script src="/TicketFaster/js/jquery-1.11.3.js"></script>
<script src="/TicketFaster/js/scripts.js"></script>
<cfset ticketid="#ticketid#">
<button id="in_testing" type="button">In Testing</button>
my js:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (#ticketid#);
$.ajax({
url: 'ticketcomponent.cfc?method=in_testing',
type: 'POST',
data: {
test: x
}
});
});
});
The big problem is that these pages are being generated dynamically, so each one will have a different ticket id. Therefore, I need to have the ticket id variable be imported rather than just hard coded in to the jquery function. So is this possible? I did not include the query because it works fine when I use it in other places, just getting the data delivered is the tough part. I appreciate any help you can give me :)
Edit: I was requested to post what I'm trying right now.
The original coldfusion is the same so I'm not going to post that again. Here is the js I'm using:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (<cfoutput>#ticketid#</cfoutput>);
alert(x);
});
});
(I also tried without the cfoutput tags)
As you can see, I'm just trying to do a simple alert to check if my variable has been correctly set. Once I get that to work, then the ajax should follow fairly quickly because I have some experience in that.
What is your specific issue?, can you share a jsfiddle?
for dynamic events replace
$("#in_testing").click(function() {});
for
$(document).on('click','#in_testing', function() {});
This value
var x = (#ticketid#);
in jquery is some like that
var x = $('#ticketid').val(); // for value or $('#ticketid') for object
you just have to take account id created dynamically

Use jQuery to determine when Django's filter_horizontal changes and then get the new data

I have a filter_horizontal selector in my Django admin that has a list of categories for products (this is on a product page in the admin). I want to change how the product change form looks based on the category or categories that are chosen in the filter_horizontal box.
I want to call a function every time a category is moved from the from or to section of the filter_horizontal.
What I have now is:
(function($){
$(document).ready(function(){
function toggleAttributeSection(choices) {
$.getJSON('/ajax/category-type/', { id: choices}, function (data, jqXHR) {
// check the data and make changes according to the choices
});
}
// The id in the assignment below is correct, but maybe I need to add option[]??
var $category = $('#id_category_to');
$category.change(function(){
toggleAttributeSection($(this).val());
});
});
})(django.jQuery);
The function never gets called when I move categories from the left side to the right side, or vice versa, of the filter_horizontal.
I assume that $category.change() is not correct, but I don't know what other events might be triggered when the filter_horizontal is changed. Also, I know there are multiple options inside of the select box. I haven't gotten that far yet, but how do I ensure all of them are passed to the function?
If anyone can point me in the right direction I would be very grateful. Thank!
You need to extend the SelectBox.redisplay function in a scope like so:
(function() {
var oldRedisplay = SelectBox.redisplay;
SelectBox.redisplay = function(id) {
oldRedisplay.call(this, id);
// do something
};
})();
Make sure to apply this after SelectBox has been initialized on the page and every time a select box refreshes (option moves, filter is added, etc.) your new function will be called.
(Code courtesy of Cork on #jquery)
I finally figured this out. Here is how it is done if anyone stumbles on this question. You need to listen for change events on both the _from and _to fields in the Django filter_horizontal and use a timeout to allow the Django javascript to finish running before you pull the contents of the _from or _to fields. Here is the code that worked for me:
var $category = $('#id_category_to');
$category.change(function(){
setTimeout(function () { toggleAttributeSection(getFilterCategoryIds()) }, 500);
});
var $avail_category = $('#id_category_from');
$avail_category.change(function(){
setTimeout(function () { toggleAttributeSection(getFilterCategoryIds()) }, 500);
});
And this is how I get the contents of the _to field:
function getFilterCategoryIds() {
var x = document.getElementById("id_category_to");
var counti;
var ids = [];
for (counti = 0; counti < x.length; counti++) {
ids.push(x.options[counti].value);
}
return ids;
}
I know it was a convoluted question and answer and people won't come across this often but hopefully it helps someone out.

Sorting Dynamic Data with Isotope

I am trying to use Isotope.js to sort data by type. There seem to be a few ways to do this however they all require that you know the sort variables before hand.
One of the best examples of what I'm talking about is found in this question.
In the example they are trying to sort by class for example group all elements with class .milk like so:
milk: function( $elem ) {
var isMilk = $elem.hasClass('milk');
return (!isMilk?' ':'');
},
A jsfiddle is provided here: http://jsfiddle.net/Yvk9q/9/
My problem:
I am pulling the categories (classes or data-type) from a user generated database. For this reason I cannot simply add all the sorting variables to the code before hand.
I played with the fiddle and got a semi working sort here: http://jsfiddle.net/BandonRandon/erfXH/1/ by using data-category instead of class. However,this just sorts all data alphabetically not by actual category.
Some possible solutions:
Use JSON to return an array of all categories and then use this to loop through classes
Use inline javascript and run a PHP loop inside a <script> tag
Write an external PHP file with a javascript header
What I'm looking for
The simplest best approach here, being if it's one of the solutions above or something different. This doesn't seem like it should need to be this complicated. So I may be over complicating this.
EDIT:
I now have a json array of my data but I can't figure out how to pass the data into the isotope settings when i try something like this
var $container = $('.sort-container');
var opts = {
itemSelector: '.member-item',
layoutMode: 'straightDown',
getSortData : {
$.getJSON( 'member-cat-json.php', function(data) {
$.each(data, function(i, item) {
var slug = data[i].slug;
slug : function( $elem ) {
var is+slug = $elem.hasClass(slug);
return (!is+slug?' ':'');
}
}
});
});
}
}
var $container = $('.sort-container');
$container.isotope(opts);
It fails because I can't use a loop inside of the plugin settings. Not sure what can be done about this though.
EDIT 2:
I found this question which seems about what I'm trying to do but unfortunately the most recent jsfiddle fails with isotope
Here is a sample of my JSON output:
{term_id:9, name:Milk, slug:milk, term_group:0, term_taxonomy_id:17...}
{term_id:9, name:Eggs, slug:eggs, term_group:0, term_taxonomy_id:17...}
I am using the slug as the class name and in my loop.
I'm not sure I entirely understand your question, but I'll state my assumptions and work from there:
You have data in a format as described above:
{term_id:9, name:Milk, slug:milk, term_group:0, term_taxonomy_id:17...}
You want to sort on the slug names, even though we do not know what the slugs will be named ahead of time.
Assuming these two things, the fiddle you've linked to is close, but has a problem due to closures which I have fixed.
As expected, your situation is similar to the one listed, except that you need to obtain the JSON data first, as you have.
var $container = $('.sort-container'),
createSortFunction = function(slug) {
return function($elem) {
return $elem.hasClass(slug) ? ' ' : '';
};
},
getSortData = function(data) {
var sortMethods = {};
for (var index in data) {
var slug = data[index].slug;
// immediately create the function to avoid
// closure problems
sortMethods[slug] = createSortFunction(slug);
}
return sortMethods;
}
$.getJSON('member-cat-json.php', function (data) {
// I'm wrapping the isotop creation inside the `getJSON`
// call, just to ensure that we have `data`
$container.isotope({
itemSelector: '.member-item',
layoutMode: 'straightDown',
getSortData: getSortData(data);
});
});

jQuery draggables - get id of dragable

Solution Found!
I found it, I was overlooking that I could just get the id of the variable item. So I put var item_id = item.attr('id'); and that was my solution. So much simpler than I thought. Thanks for your help everyone!
Okay, so I have multiple draggable elements in jQuery, they are all images, but each one has their own ID. Anyway, I have set up a function that is preformed once the image is dropped onto the droppable. I want to be able to pull the id of the image so I may process what image has been dropped in my database.
function foundationsInSpot(drag_item,spot)
{
var oldSpotItem = $(spot).find('img');
if(oldSpotItem.length>0) {
oldSpotItem.appendTo('#foundationinv').draggable({ revert: 'invalid' });
}
var item = $('<img />');
var item_id = "";
var bid = "<?= $bid ?>";
item.attr('src',drag_item.attr('src')).attr('id',drag_item.attr('id')).attr('class',drag_item.attr('class')).appendTo(spot).draggable({ revert: 'invalid' });
drag_item.remove();
alert('BenID: ' + bid + ' Foundation: ' + item_id);
var dataString = 'item_id='+ item_id + '&bid=' + bid;
$.ajax({
type: "POST",
data: dataString,
url: "http://motb.isgreat.org/objects/pfoundations.php",
});
}
So that's my code. I need to find item_id. Here was my guess var item_id = $('<img />').attr('id'); but it returned blank information. I also tried var item_id = ui.draggable.attr("id"); and that just stopped the rest of my function. Any ideas? Thanks in advance.
By the way here is how my draggable items look like.
<img src='http://motb.isgreat.org/objects/khhhqw4s.png' class='object foundation' id='khhhqw4s'/>
UPDATE
I moved the var item_id = ui.draggable.attr("id"); above the if statement, and now I get undefined. So I am unsure where to go from here, but I am aware my AJAX call is operating correctly as it is updating my database with undefined.
UPDATE - Again
So here is how I am calling my function if this makes it easier.
$(".foundations").draggable({ revert: 'invalid'}).addTouch;
$('#foundationinv').droppable({accept: '.foundations'});
$("#foundations").droppable({ accept: '.foundations'})
$('#foundations,#foundationinv').bind('drop', function(ev,ui) { foundationsInSpot(ui.draggable,this); });
I have never done anything like this before, so It's really beyond me. If you would like to see the page in person, go to http://motb.isgreat.org/ and click the login button, and use testbot for both the username and the password. To see where the draggables are, on the left side there is this big box with 4 smaller ones below it, click above the small box where the word is foundations. I am trying to drag those objects that appear into the small box. You can see an alert with the information I am trying to pass. Feel free to check my source for any issues, the items are called up from my database, so my PHP is probably missing from your source.
I found it, I was overlooking that I could just get the id of the variable item. So I put var item_id = item.attr('id'); and that was my solution. So much simpler than I thought. Thanks for your help everyone!
inside the droppable you have a property called drop
$("#destination").droppable({
hoverClass: 'ui-state-hover',
helper: 'clone',
cursor: 'move',
drop: function(event, ui) {
$(this).addClass('ui-state-highlight');
$(ui.draggable).addClass('ui-state-highlight');
$(ui.draggable).draggable('disable');
console.log('Dragged: ' + $(ui.draggable).attr("id"));
}
});
use that method to call what object was dropped calling $(ui.draggable).attr("id")
if you see the object, ui.draggable is only the HTML, soon you wrapp it with $() you will be able to do any jQuery operation with it.
http://jsbin.com/iboli4/edit
open the Console in Inspector to see the id's

Categories