jQuery $(this).addClass not working - javascript

I have a list of textboxes in which a user can drop a letter but when a wrong letter is dropped inside the textbox I want to addClass("danger") I want to addClass only on the wrong letter textbox I have also attached a screenshot to illustrate the problem.
The textbox has a class with the name of box assigned.
Now my drop function is given below.
function dropabc(event) {
if ($(objBox).attr("correct1") != event.target.id) {
$(".imageError").fadeIn('slow').delay(1000).hide(0);
console.log("error");
$(this).addClass('danger');
} else {
console.log(event.target.id);
console.log("ok");
}
}
$(this).addClass("danger")
However, this is not working, I only want to add the danger class to the box on which a wrong value is dropped.
//makes all the textbox red
$(".box").addClass("danger")
Any help would be very appreciated!
This is the jQuery UI drag and droppable function which is working fine:
var objBox;
$('.drag').draggable({
revert: true,
helper: 'clone',
cursor: 'pointer',
start: function(event, ui) {
$(this).fadeTo('fast', 0.5);
objBox=$(this);
},
stop: function(event, ui) {
$(this).fadeTo(0, 1);
}
});
$("#textbox, .box").droppable({
hoverClass: "hoverPath",
drop: function(event, ui) {
var $this = $(this);
if ($this.val() == '') {
$this.val(ui.draggable.text());
$(this).addClass("checkDiv");
$(this).each(function(i, el){
$(el).addClass(myid[3]);
});
}
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
console.log(empty.length);
}
else{
console.log("done");
}
}
});
This is the PHP code which is echo the number of textbox:
for($x = 0 ; $x < count($code_words); $x++){
echo "<input id='".$code_words[$x]."' ondrop='dropabc(event)' class='box' type='textbox'/>";
}

You're just running a function when you embed the ondrop event inside your input tag.
So instead of embedding it try using the jQuery on("drop").
$(document).on("drop", ".box", function(event){
if ($(objBox).attr("correct1") != event.target.id) {
$(".imageError").fadeIn('slow').delay(1000).hide(0);
console.log("error");
$(this).addClass('danger');
} else {
console.log(event.target.id);
console.log("ok");
}
})
Great it helped you :)
Cheers,

Related

Alerting Order of Dropped Elements WITHOUT using jQuery sortable

https://jsfiddle.net/ianderso222/y9ynouxs/36/
I hope this makes sense, If I need to elaborate I will do so.
Right now the code is working pretty well, doing everything I need it to except this one issue. I just need to alert the order that the squares have been dropped in, after all 4 have been placed.
So, if square4 is placed in the large container, that would show up first in the alert. If square2 is in the last, smallest box it would be last in the list, and so on.
I would use sortable but I am afraid it would not work with the current setup. The resizing to different sized containers would not work, or at least I was not able to get it to work. If there is a way to keep the current structure of resizing to fill container and sliding into place I would say do that, but from everything I have seen I feel I would have to essentially start from scratch.
Here is the JavaScript, pardon the messy code:
$('.holderList li').droppable({
drop: function(event, ui) {
var droppable = $(this);
var draggable = ui.draggable;
console.log(draggable.attr('id') + ' is ' + droppable.attr('id'));
var $this = $(this);
ui.draggable.position({
my: "center",
at: "center",
of: $this,
using: function(pos) {
$(this).animate(pos, 200, "linear");
}
});
ui.draggable.addClass('dropped');
ui.draggable.data('droppedin', $(this));
$(this).droppable('disable');
setTimeout(function() {
var dragID = ui.draggable;
if (!$(".ui-droppable").not(".ui-droppable-disabled").length) {
alert(draggable.attr('id'));
}
}, 400);
},
});
$(".square").draggable({
stack: ".square",
revert: function(event, ui) {
//overwrite original position
$(this).data("ui-draggable").originalPosition = {
width: 50,
height: 50
}
//return boolean
return !event;
},
drag: function(event, ui) {
var draggable = $(this).data("ui-draggable");
$.each(draggable.snapElements, function(index, element) {
ui = $.extend({}, ui, {
snapElement: $(element.item),
snapping: element.snapping
});
if (element.snapping) {
if (!element.snappingKnown) {
element.snappingKnown = true;
draggable._trigger("snapped", event, ui);
}
} else if (element.snappingKnown) {
element.snappingKnown = false;
draggable._trigger("snapped", event, ui);
}
});
if ($(this).data('droppedin')) {
$(this).data('droppedin').droppable('enable');
$(this).data('droppedin', null)
$(this).removeClass('dropped')
}
},
snap: ".holder",
snapMode: "inner",
snapTolerance: 8,
snapped: function(event, ui) {
var squareWidth = ui.snapElement.width();
var squareHeight = ui.snapElement.height();
ui.helper.css({
width: squareWidth,
height: squareHeight
});
}
});
Take a look at my solution:
Demo
First it assigns a data-current attribute to the droppable holder on every drop and sets it to the id of the draggable.
Then it itterates trough all the .holder elements and prints their data-current
Simple but works.
// On single drop
drop: function(event,ui){
...
droppable.attr('data-current', draggable.attr('id') );
}
//On all dropped
$('.holder').each(function(el){
console.log($(this).attr('data-current'));
});

Jquery Ui AutoComplete is not working with keyup/down when used with label value

When using keyup keydown to select option from autocomplete list textbox is showing value. But incase of selection from mouse it is working properly.
JsFiddle - http://jsfiddle.net/0c21r1pe/1
$("#promoteActionTextBox").autocomplete({
source: actionNames,
minLength: 0,
select: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
$('#promoteActionError').hide();
$(this).attr('actionId', ui.item.value);
},
change: function (event, ui) {
if (!ui.item) {
$(this).val('');
}
else {
$('#promoteActionError').hide();
$(this).val(ui.item.label);
$(this).attr('actionId', ui.item.value);
}
}
}).focus(function (event, ui) {
event.preventDefault();
$('#promoteActionTextBox').autocomplete("search");
this.value = ui.item.label;
});
change the object property name from value to something else and it works
WORKING DEMO
UPDATE
How about THIS FIDDLE
I added a code which removes the event which is responsible for that effect.
create:function(){
$('.ui-autocomplete').unbind('menufocus');
}
select: function(event, ui) {
event.preventDefault(); // Add on keyboard keyup, keydown is working well
$("#id_value").val(ui.item.value);
$("#id_label").val(ui.item.label);
},
focus: function( event, ui ) {
event.preventDefault(); // Add on keyboard keyup, keydown is working well
$("#id_value").val(ui.item.value);
$("#id_label").val(ui.item.label);
}

Create link in JQuery Autocomplete

I am having difficulty figuring where to insert and how to make a click function when users click/select an autocomplete item. I then want to do a DB query with the clicked item.
My current autocomplete script:
$("#search_customer").autocomplete({
source: "search.php",
minLength: 1,
response: function(event, ui) {
if (!ui.content.length) {
var create_customer = alert('bla bla...');
if (create_customer)
{
console.log('yes');
}
else
{
console.log('no');
}
}
}
});
Use select callback of jquery ui autocomplete
e.g
$("#search_customer").autocomplete({
source: "search.php",
minLength: 1,
select: function(event,ui) {
var label = ui.item.label; // label of selected item
var value = ui.item.value; // value of selected item
// then make an ajax call here to get the data from db.
},
response: function(event, ui) {
if (!ui.content.length) {
var create_customer = alert('bla bla...');
if (create_customer)
{
console.log('yes');
}
else
{
console.log('no');
}
}
}
});
Hope this helps.

only allow one object to be dropped jquery

$("li").draggable({
helper: "clone"
});
$("#div1").droppable({
drop: function (event, ui) {
$("<p></p>").appendTo("#div1");
}
});
I have objects in a list that can be dragged and dropped into a div named div1. But when I drop one into the div i don't want to be able to drop another into it. I have tried using, for, if and while loops with a count.
Here is a full solution, it allows only one item dropped, but also, if one exists, it gets replaced on the next drop with the new one. (Usefull if someone changes their mind. Just call
refreshDragDrop(dragClassName,dropDivId);
refreshDragDrop = function(dragClassName,dropDivId) {
$( "." + dragClassName ).draggable({
connectToSortable: "#" + dropDivId,
helper: "clone",
revert: "invalid"
});
$("#" + dropDivId).droppable({
accept: '.' + dragClassName,
drop: function (event, ui) {
var $this = $(this),
maxItemsCount = 1;
if ($this.children('div').length == maxItemsCount ){
//more than one item,just replace
$(this).html($(ui.draggable).clone());
} else {
$(this).append($(ui.draggable).clone());
}
}
});
}
This should help:
drop: function (event, ui) {
var $this = $(this),
maxItemsCount = 1;
if ($this.children('li').length > maxItemsCount ){
ui.sender.draggable('cancel');
alert("To much items!");
}
}

update the unselectable value (jquery)

i'm using selectable jquery, i want to cater the value for selectable once the use select or unselect the item. My problem is, the last value of unselectable won't update.
Full code here http://jsfiddle.net/duQH6/ When I select Mon and Tue, then I unselect the Tue, the value is updated, but then when I click Mon, the value is not updated. Please advice.
Here my jquery code
$(function() {
$("#selectday1").bind('mousedown', function (e) {
e.metaKey = true;
}).selectable();
});
$('document').ready(function(){
$( "#selectday1" ).selectable({
selected: function(event, ui) {
var result=[];
jQuery(".ui-selected", this).each(function()
{
result.push(this.id);
$("#days").val(result.join(','))
});
}
});
$( "#selectday1" ).selectable({
unselected: function(event, ui) {
var result=[];
jQuery(".ui-selected", this).each(function()
{
result.push(this.id);
$("#days").val(result.join(','))
});
}
});
});
Thanks..
The problem is, you are updating the days value within the each loop, so when you unselect the last element the loop callback is never executed, that is why it is happening.
The days value is supposed to be updated once the each() loop is completed.
$(document).ready(function () {
$("#selectday1").selectable({
selected: function (event, ui) {
var result = [];
jQuery(".ui-selected", this).each(function () {
result.push(this.id);
});
$("#days").val(result.join(','))
},
unselected: function (event, ui) {
var result = [];
jQuery(".ui-selected", this).each(function () {
result.push(this.id);
});
$("#days").val(result.join(','))
}
});
});
Demo: Fiddle
But it can be simplified to
jQuery(function ($) {
function serialize(event, ui) {
var result = $(this).find(".ui-selected").map(function () {
return this.id;
}).get();
$("#days").val(result.join(','))
}
$("#selectday1").selectable({
selected: serialize,
unselected: serialize
});
});
Demo: Fiddle

Categories