I'm using jquery ui for dragging items, so I have an array similar to:
var animals = ['cat', 'dog', 'monkey'];
var output = [];
for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '</p>');
}
$('#list').html(output.join(""));
So I get this on the page, what I want to do is if I drag "cat" to dragging zone, I would like to remove it from the array automatically. New array should have only "dog" and "monkey" in it and that should be showed on the page.
<div class="col-xs-2">
<a href="#">
<img id="drag-cat" class="drag-img" src="images/cat.png" alt="" />
</a>
</div>
That is my html part, so when I drag it and this item is showed in that drag div, I would like to update array.
Any suggestions?
Thanks.
EDIT:
JS Fiddle
Use Array#splice to remove item from array by specifying the index
Use String#split to get name from id attribute as there is no other reference
Re-bind the output array considering removed item
$(function() {
$(".drag-main img").draggable({
revert: "invalid",
refreshPositions: true,
drag: function(event, ui) {
ui.helper.addClass("draggable");
},
stop: function(event, ui) {
ui.helper.removeClass("draggable");
var image = this.src.split("/")[this.src.split("/").length - 1];
}
});
$(".animals-box").droppable({
drop: function(event, ui) {
if ($(".animals-box img").length == 0) {
$(".animals-box").html("");
}
ui.draggable.addClass("dropped");
var elem = ui.draggable[0].getAttribute('id').split('-')[1];
animals.splice(animals.indexOf(elem), 1);
var output = [];
for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '</p>');
}
$('#list').html(output.join(""));
$(".animals-box").append(ui.draggable);
}
});
});
var animals = ['cat', 'dog', 'monkey'];
var output = [];
for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '</p>');
}
$('#list').html(output.join(""));
.drag-main img {
width: 75px;
}
.animals-box {
background-color: gray;
height: 100px;
width: 100%;
}
.animals-box img {
float: left;
}
.draggable {
filter: alpha(opacity=80);
opacity: 0.8;
}
.dropped {
position: static;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<div class="drag-main">
<div class="row">
<div class="col-xs-2">
<a href="#">
<img id="drag-cat" class="drag-img" src="http://i.amz.mshcdn.com/KRUEW_Zm_0UvTD97QnKID9MUqmk=/150x150/2012%2F12%2F04%2Fd0%2Fcat.c4A" alt="" />
</a>
</div>
<div class="col-xs-2">
<a href="#">
<img id="drag-dog" class="drag-img" src=" http://www.dogisto.com/wp-content/uploads/2016/03/dog-abandoned-150x150.jpg" alt="" />
</a>
</div>
</div>
</div>
<div class="animals-box"></div>
<hr>
<div id="list">
</div>
Fiddle Demo
Using data-* attribute
$(function() {
$(".drag-main img").draggable({
revert: "invalid",
refreshPositions: true,
drag: function(event, ui) {
ui.helper.addClass("draggable");
},
stop: function(event, ui) {
ui.helper.removeClass("draggable");
var image = this.src.split("/")[this.src.split("/").length - 1];
}
});
$(".animals-box").droppable({
drop: function(event, ui) {
if ($(".animals-box img").length == 0) {
$(".animals-box").html("");
}
ui.draggable.addClass("dropped");
var elem = ui.draggable[0].dataset.name;
animals.splice(animals.indexOf(elem), 1);
var output = [];
for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '</p>');
}
$('#list').html(output.join(""));
$(".animals-box").append(ui.draggable);
}
});
});
var animals = ['cat', 'dog', 'monkey'];
var output = [];
for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '</p>');
}
$('#list').html(output.join(""));
.drag-main img {
width: 75px;
}
.animals-box {
background-color: gray;
height: 100px;
width: 100%;
}
.animals-box img {
float: left;
}
.draggable {
filter: alpha(opacity=80);
opacity: 0.8;
}
.dropped {
position: static;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<div class="drag-main">
<div class="row">
<div class="col-xs-2">
<a href="#">
<img id="drag-cat" data-name="cat" class="drag-img" src="http://i.amz.mshcdn.com/KRUEW_Zm_0UvTD97QnKID9MUqmk=/150x150/2012%2F12%2F04%2Fd0%2Fcat.c4A" alt="" />
</a>
</div>
<div class="col-xs-2">
<a href="#">
<img id="drag-dog" data-name="dog" class="drag-img" src=" http://www.dogisto.com/wp-content/uploads/2016/03/dog-abandoned-150x150.jpg" alt="" />
</a>
</div>
</div>
</div>
<div class="animals-box"></div>
<hr>
<div id="list">
</div>
You can get the dropped elemenent id and remove it from the array in the drop event like:
var index = animals.indexOf( ui.draggable.attr("id").replace('drag-',''));
animals.splice(index, 1);
Demo: https://jsfiddle.net/th01sw16/2/
Related
In the wishlist ui function, I append items to the wishlist by checking the .wish-btn. I want to simulate items already added to the list so I need to run the function on load so that all of the items have been checked.
How do I run the function on load so that all of the items are:
Already checked
Appended to the list
var wish = {
items: []
};
var update_product = function(product) {};
$(function() {
//Add to wish
var addToWish = function(product, qty) {
qty = qty || 1;
var wish = getWish();
var indexOfId = wish.items.findIndex(x => x.id == product.id);
if (indexOfId === -1) {
wish.items.push({
id: product.id,
img: product.img,
name: product.name
});
$parent = $("#" + product.id).closest(".product");
$parent
.find(".wish-icon")
.addClass("active")
.attr("data-prefix", "fas");
} else {
wish.items[indexOfId].qty++;
wish.items[indexOfId].stock = Number(product.stock);
}
//Update popup wish
updateWish(wish);
};
//Remove from wish on id
var removeFromWish = function(id) {
var wish = getWish();
var wishIndex = wish.items.findIndex(x => x.id == id);
wish.items.splice(wishIndex, 1);
$parent = $("#" + id).closest(".product");
$parent
.find(".wish-icon")
.first()
.removeClass("active")
.attr("data-prefix", "far");
//Update popup wish
updateWish(wish);
};
var getProductValues = function(element) {
var productId = $(element)
.closest(".product")
.find(".item__title")
.attr("id");
var productImg = $(element)
.closest(".product")
.find(".item__img")
.attr("src");
var productName = $(element)
.closest(".product")
.find(".item__title")
.html();
return {
id: productId,
img: productImg,
name: productName
};
};
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
if ($(this).is(":checked")) {
addToWish({
id: product.id,
img: product.img,
name: product.name
});
} else {
removeFromWish(product.id);
}
});
//Update wish html to reflect changes
var updateWish = function(wish) {
//Add to shopping wish dropdown
$(".wishlist__items").html("");
for (var i = 0; i < wish.items.length; i++) {
$(".wishlist__items").append(
"<li class='wish__item'>" +
'<div class="wish__thumb">' +
"<img src='" +
wish.items[i].img +
"' />" +
"</div>" +
'<div class="wish__info">' +
'<div class="wish-name">' +
wish.items[i].name +
"</div>" +
"</div>" +
'<div class="wish__remove">' +
'<label class="wish__label">' +
'<input type="checkbox" id="my-wish-remove' +
i +
'" class="my-wish-remove" aria-hidden="true">' +
"<i class='fas fa-heart'></i>" +
"</div>" +
"</div>"
);
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
$("#" + wish.items[currentIndex].id).parents().find($(".wish-btn > input")).prop("checked", false);
removeFromWish(wish.items[currentIndex].id);
}, 400);
});
})();
}
};
//Get Wish
var getWish = function() {
var myWish = wish;
return myWish;
};
});
img {
width: 50px;
}
.my-wish-add {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
}
.wish-btn {
position: relative;
}
.wish-btn input {
position: absolute;
opacity: 0;
top: 0;
left: 0;
right: 0;
bottom: 0;
cursor: pointer;
}
.wishlist__list {
right: 0;
width: 320px;
position: absolute;
padding: 20px;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="product">
<div id='headphones' class='item__title'>Item 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'>
<i class="wish-icon far fa-heart"></i>
</input>
</label>
</div>
<div class="product">
<div class="items__cart">
<div id='backpack' class='item__title'>Item 2</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'>
<i class="wish-icon far fa-heart"></i>
</input>
</label>
</div>
</div>
<div class="product">
<div class="items__cart">
<div id='handbag' class='item__title'>Item 3</div>
<img class="item__img" src="https://qph.fs.quoracdn.net/main-qimg-de7d9680c4460296e461af9720a77d64">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'>
<i class="wish-icon far fa-heart"></i>
</input>
</label>
</div>
</div>
</div>
`
Follow charlietfl's answer, then you will get an error:
TypeError: getWish is not a function
Then you have to move your change event handler to the bottom below getWish and updateWish function, because they need to be declared first to be used by the event handler.
var wish = {
items: []
};
var update_product = function(product) {};
$(function() {
//Add to wish
var addToWish = function(product, qty) {
qty = qty || 1;
var wish = getWish();
var indexOfId = wish.items.findIndex(x => x.id == product.id);
if (indexOfId === -1) {
wish.items.push({
id: product.id,
img: product.img,
name: product.name
});
$parent = $("#" + product.id).closest(".product");
$parent
.find(".wish-icon")
.addClass("active")
.attr("data-prefix", "fas");
} else {
wish.items[indexOfId].qty++;
wish.items[indexOfId].stock = Number(product.stock);
}
//Update popup wish
updateWish(wish);
};
//Remove from wish on id
var removeFromWish = function(id) {
var wish = getWish();
var wishIndex = wish.items.findIndex(x => x.id == id);
wish.items.splice(wishIndex, 1);
$parent = $("#" + id).closest(".product");
$parent
.find(".wish-icon")
.first()
.removeClass("active")
.attr("data-prefix", "far");
//Update popup wish
updateWish(wish);
};
var getProductValues = function(element) {
var productId = $(element)
.closest(".product")
.find(".item__title")
.attr("id");
var productImg = $(element)
.closest(".product")
.find(".item__img")
.attr("src");
var productName = $(element)
.closest(".product")
.find(".item__title")
.html();
return {
id: productId,
img: productImg,
name: productName
};
};
//Update wish html to reflect changes
var updateWish = function(wish) {
//Add to shopping wish dropdown
$(".wishlist__items").html("");
for (var i = 0; i < wish.items.length; i++) {
$(".wishlist__items").append(
"<li class='wish__item'>" +
'<div class="wish__thumb">' +
"<img src='" +
wish.items[i].img +
"' />" +
"</div>" +
'<div class="wish__info">' +
'<div class="wish-name">' +
wish.items[i].name +
"</div>" +
"</div>" +
'<div class="wish__remove">' +
'<label class="wish__label">' +
'<input type="checkbox" id="my-wish-remove' +
i +
'" class="my-wish-remove" aria-hidden="true">' +
"<i class='fas fa-heart'></i>" +
"</div>" +
"</div>"
);
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
$("#" + wish.items[currentIndex].id).parents().find($(".wish-btn > input")).prop("checked", false);
removeFromWish(wish.items[currentIndex].id);
}, 400);
});
})();
}
};
//Get Wish
var getWish = function() {
var myWish = wish;
return myWish;
};
// Move this block to the bottom after you have defined all functions
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
if ($(this).is(":checked")) {
addToWish({
id: product.id,
img: product.img,
name: product.name
});
} else {
removeFromWish(product.id);
}
}).prop('checked', true).change();
});
img {
width: 50px;
}
.my-wish-add {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
}
.wish-btn {
position: relative;
}
.wish-btn input {
position: absolute;
opacity: 0;
top: 0;
left: 0;
right: 0;
bottom: 0;
cursor: pointer;
}
.wishlist__list {
right: 0;
width: 320px;
position: absolute;
padding: 20px;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="product">
<div id='headphones' class='item__title'>Item 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'/>
<i class="wish-icon far fa-heart">click to wish</i>
</label>
</div>
<div class="product">
<div class="items__cart">
<div id='backpack' class='item__title'>Item 2</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'/>
<i class="wish-icon far fa-heart">click to wish</i>
</label>
</div>
</div>
<div class="product">
<div class="items__cart">
<div id='handbag' class='item__title'>Item 3</div>
<img class="item__img" src="https://qph.fs.quoracdn.net/main-qimg-de7d9680c4460296e461af9720a77d64">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'/>
<i class="wish-icon far fa-heart">click to wish</i>
</label>
</div>
</div>
</div>
You can trigger a change right after you create a change event listener by chaining change() with no arguments to it.
Using prop('checked', true) will check them and you can chain that as well
$(selector).on('change', function(evt){
// do stuff when change occurs
// now check it and trigger change
}).prop('checked', true).change()
DEMO
Hi,
on click of images I'am passing the Image Name (attribute) to an Array, which is working fine, but whenever user click again to UnSelect, I'am trying to REMOVE Current Name($(this)), which is not happening, Instead Its being Removed Completely (Empty Array).
and also every time comma is appending for 1st element :-(
JS :
questionCount = 0;
$('.q2 .product-multiple').on('click',function(e){
if($(this).hasClass('selectTag')){
questionCount--;
$(this).removeClass('selectTag');
removeItem = "Removing Clicked element Name - " + $(this).find('img').attr('name')
alert(removeItem);
console.log("Should be Removed here.. " +" "+ getTagsNameArray)
}
else {
questionCount++;
$(this).addClass('selectTag');
getTagsNameArray = new Array();
getTagsName = getTagsName + "," + $(this).find('img').attr('name');
getTagsNameArray.push(getTagsName)
console.log("Passing Value in Array - " +" "+ getTagsNameArray)
}
});
$('.q2-get-answer').on('click', function(){
getTagsName = getTagsName +" / "+ $('.q2-answer').find('.product-multiple.selectTag img').attr('name');
alert(getTagsName)
console.log(getTagsName);
})
html :
<div class="q2">
<label for="q2">What type of symptoms that your child has?</label>
<div class="q2-answer" id="q2">
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="gassy">
<div>Gassy</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="fussy">
<div>Fussy</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="diahrea">
<div>Diahrea</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="spitup">
<div>Spit Up</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="constipation">
<div>Constipation</div>
</div>
</div>
<div class="q2-get-answer">
Q3 click me
</div>
</div>
Thanks for Answer!!
can i create a common function for this, as there are many questions with same functionality ?
Any Thoughts ?
Thanks Again
Try this.
var getQ1Answer, getQ2Answer, getQ3Answer, getQ4Answer, getQ5Answer, getQ6Answer, sliderValue, selectMonth, q1answer, getTags;
var getTagsName = "";
var getTagsNameArray = new Array();
questionCount = 0;
$('.q2 .product-multiple').on('click', function(e) {
if ($(this).hasClass('selectTag')) {
questionCount--;
$(this).removeClass('selectTag');
var index = getTagsNameArray.indexOf($(this).find('img').attr('name'));
if (index !== -1) {
getTagsNameArray.splice(index, 1);
}
} else {
questionCount++;
$(this).addClass('selectTag');
getTagsNameArray.push($(this).find('img').attr('name'));
}
});
You need to declare array outside the function. You pushed items in array with , which is not needed. Your JS code will look like:
var getQ1Answer, getQ2Answer, getQ3Answer, getQ4Answer, getQ5Answer, getQ6Answer, sliderValue, selectMonth, q1answer, getTags;
var getTagsName = "";
var getTagsNameArray = new Array(); // here you should create an array
questionCount = 0;
$('.q2 .product-multiple').on('click',function(e){
if($(this).hasClass('selectTag')){
questionCount--;
$(this).removeClass('selectTag');
removeItem = "Removing Clicked element Name - " + $(this).find('img').attr('name')
alert(removeItem);
var doubleSelect = $(this).find('img').attr('name');
var index = getTagsNameArray.indexOf(doubleSelect);
console.log(index)
if (index > -1) {
getTagsNameArray.splice(index, 1);
}
console.log("Should be Removed here.. " +" "+ getTagsNameArray)
}
else {
questionCount++;
$(this).addClass('selectTag');
getTagsNameArray.push($(this).find('img').attr('name')); //change is here
console.log("Passing Value in Array - " +" "+ getTagsNameArray)
}
});
$('.q2-get-answer').on('click', function(){
getTagsName = getTagsName +" / "+ $('.q2-answer').find('.product-multiple.selectTag img').attr('name');
alert(getTagsName)
console.log(getTagsName);
})
Fiddle
You are appending a string to an array, which transforms the array into a string: getTagsName + ","
Instead of appending a string to the array, you need to add a new element to the Array by using getTagName.push($(this).find('img').attr('name')). You can remove items by using indexOf() and splice().
If you want to print the array, simply use getTagsName.join(). This will turn your array in a comma-seperated string.
It's because you create a new getTagsNameArray array everytime you unselect a $('.q2 .product-multiple'). See the else statement in the click handler.
If I understand your question correctly, you want an array with the name attributes of the selected images? In that case:
declare and create the getTagsNameArray outside the click handler
on click of an image, add the name to the array
on click again (so unselecting), find the name in the array and
remove it.
https://jsfiddle.net/gcke1msx/7/
var getTagsNameArray = [];
$('.q2 .product-multiple').on('click', function(e) {
// get the name of the image
var name = $(this).find('img').attr('name');
if($(this).hasClass('selectTag')) {
// it was selected, now unselected
// so remove its name from the array
// see: http://stackoverflow.com/questions/5767325/remove-a-particular-element-from-an-array-in-javascript
$(this).removeClass('selectTag');
var index = getTagsNameArray.indexOf(name);
getTagsNameArray.splice(index, 1);
} else {
// selected it
// and add name to array
$(this).addClass('selectTag');
getTagsNameArray.push(name);
}
});
$('.q2-get-answer').on('click', function(){
alert('selected: ' + getTagsNameArray.join(', '));
})
First of all, you should not have so many variables. Just a variable to push/splice item from/to array.
Array.prototype.splice() => The splice() method changes the content of an array by removing existing elements and/or adding new elements.
Syntax: array.splice(start, deleteCount[, item1[, item2[, ...]]])
var getTagsNameArray = [];
$('.q2 .product-multiple').on('click', function(e) {
var item = $(this).find('img').attr('name');
if ($(this).hasClass('selectTag')) {
$(this).removeClass('selectTag');
getTagsNameArray.splice(getTagsNameArray.indexOf(item), 1);
} else {
$(this).addClass('selectTag');
getTagsNameArray.push(item);
}
console.log(getTagsNameArray.join(', '));
});
$('.q2-get-answer').on('click', function() {
console.log(getTagsNameArray.join(', '));
})
.product-multiple {
float: left;
margin: 10px;
}
.product-multiple img {
width: 200px;
height: 150px;
}
.product-multiple img:hover {
cursor: pointer;
}
.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-widget-header .ui-state-default {
cursor: pointer;
}
.digestive-tool {
padding: 10px;
margin: 10px;
border: 1px solid #ccc;
}
.digestive-tool .q1-answer li,
.digestive-tool .q2-answer li,
.digestive-tool .q3-answer li,
.digestive-tool .q4-answer li,
.digestive-tool .q5-answer li,
.digestive-tool .q6-answer li {
list-style-type: none;
display: inline-block;
}
.digestive-tool .q1-get-answer,
.digestive-tool .q2-get-answer,
.digestive-tool .q3-get-answer,
.digestive-tool .q4-get-answer,
.digestive-tool .q5-get-answer,
.digestive-tool .q6-get-answer {
border: 1px solid #f00;
padding: 10px;
display: inline-block;
cursor: pointer;
}
.digestive-tool .product,
.digestive-tool .product-multiple {
display: inline-block;
}
.digestive-tool .product img,
.digestive-tool .product-multiple img {
width: 150px;
height: 180px;
cursor: pointer;
}
.selectTag {
border: 2px solid #00257a;
}
.q2-get-answer {
margin-top: 20px;
clear: left;
border: 1px solid #900;
background: #f00;
cursor: pointer;
width: 200px;
padding: 20px;
color: #fff;
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="q2">
<label for="q2">What type of symptoms that your child has?</label>
<div class="q2-answer" id="q2">
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="gassy">
<div>Gassy</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="fussy">
<div>Fussy</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="diahrea">
<div>Diahrea</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="spitup">
<div>Spit Up</div>
</div>
<div class="product-multiple">
<img alt="doctor select" src="http://i.istockimg.com/file_thumbview_approve/45921804/5/stock-photo-45921804-lake-view.jpg" name="constipation">
<div>Constipation</div>
</div>
</div>
<div class="q2-get-answer">
Q3 click me
</div>
</div>
Fiddle here
Here is a live demo
https://jsfiddle.net/soonsuweb/4ea54xxu/3/
You can use array.push, splice, join.
var selected = [];
$('.q2 .product-multiple').on('click',function (e) {
if($(this).hasClass('selectTag')){
$(this).removeClass('selectTag');
var name = $(this).find('img').attr('name');
// remove the name from selected
for (var i=0; i<selected.length; i++) {
if (name === selected[i]) {
selected.splice(i, 1);
}
}
console.log("Should be Removed here.. ", name);
console.log("Passing Value in Array - ", selected.join(', '))
}
else {
$(this).addClass('selectTag');
var name = $(this).find('img').attr('name');
selected.push(name);
console.log("Passing Value in Array - ", selected.join(', '))
}
});
$('.q2-get-answer').on('click', function () {
alert(selected.join(', '));
console.log(selected.join(', '));
});
I'm having trouble getting the id of the outer div the draggable element is being taken from.
Here is my HTML
http://dev.eteacher.online/taskAssets/cup.jpg'/>
///Droppables ".snap"
<div id="0" class='col-word'><p class="letters">c</p></div>
<div id="1" class='col-word snap' style=""><p class="letters">__</p></div>
<div id="2" class='col-word snap' style=""><p class="letters">__</p></div>
///Draggables
<div id="comparison">
<div id="v" class='col-letter'><p class="letters">v</p></div>
<div id="p" class='col-letter'><p class="letters">p</p></div>
<div id="u" class='col-letter'><p class="letters">u</p></div>
</div>
Then I have the important jQuery
var beh = new Array();
var beh2 = "";
var MyVar = "";
$(".col-letter").draggable({ cursor: 'move', snap: '.snap',
revert : function(event, ui) {
// on older version of jQuery use "draggable"
// $(this).data("draggable")
// on 2.x versions of jQuery use "ui-draggable"
// $(this).data("ui-draggable")
$(this).data("ui-draggable").originalPosition = {
top : 0,
left : 0
};
// return boolean
return !event;
// that evaluate like this:
// return event !== false ? false : true;
},
drag: function(event, ui){
if($(this).data('droppedin')){
$(this).data('droppedin').droppable('enable');
$(this).data('droppedin',null);
$(this).removeClass( 'dropped' );
MyVar = $(this).closest(".col-word").attr("id");
alert(MyVar);
beh[MyVar] = "";
alert(beh);
}
}
});
$(".snap").droppable({
hoverClass: 'hovered',
tolerance: 'pointer',
drop: function(event, ui) {
var drop_p = $(this).offset();
var drag_p = ui.draggable.offset();
var left_end = drop_p.left - drag_p.left;
var top_end = drop_p.top - drag_p.top ;
ui.draggable.animate({
top: '+=' + top_end,
left: '+=' + left_end
});
ui.draggable.addClass( 'dropped' );
ui.draggable.data('droppedin',$(this));
$(this).droppable('disable');
}
});
$( ".snap" ).on( "drop", function( event, ui ) {
MyVar = $(this).parent().attr('id');
beh[MyVar] = ui.draggable.attr('id');
alert(beh[MyVar] + " " + MyVar);
// alert(beh);
//beh[] = new Array($(this).attr('id'), ui.draggable.attr('id'));
//alert(beh);
});
Basically you can drag divs in and out of the .snap class. I want to get the id of the .snap class when I drag the divs off of the .snap.
I'm having trouble doing this. The closest function is bringing me undefined!
Any ideas?
EDIT Goal: The goal is to know which id for each col-letter gets placed on which .snap class.
The way to I thought it out was to have a get request once a button is pressed such that the position and the letter are provided.
For example, if you place id=v on id=1. the get request will enable /1v.
EDIT 2
This worked!
$(".snap").on("drop", function(event, ui) {
MyVar = ui.helper.attr('id');
beh[MyVar] = $(this).attr('id') + ui.helper.attr('id');
alert(beh[MyVar]);
});
But it makes my join command stop working!
$( "#done" ).click(function(){
beh2 = beh.join("");
var link = "/task/fillLetters/response/"+ beh2;
alert(beh2);
window.location.replace(link);
});
Any ideas?
I think this is what you need
fiddle link https://jsfiddle.net/bksL352s/
var beh = new Array();
var beh2 = "";
var MyVar = "";
$(".col-letter").draggable({
cursor: 'move',
snap: '.snap',
revert: function(event, ui) {
$(this).data("ui-draggable").originalPosition = {
top: 0,
left: 0
};
return !event;
},
drag: function(event, ui) {
if ($(this).data('droppedin')) {
$(this).data('droppedin').droppable('enable');
$(this).data('droppedin', null);
$(this).removeClass('dropped');
MyVar = $(this).attr('data-dropped-Id');
alert(MyVar);
beh[MyVar] = "";
alert(beh);
}
}
});
$(".snap").droppable({
hoverClass: 'hovered',
tolerance: 'pointer',
drop: function(event, ui) {
var drop_p = $(this).offset();
var drag_p = ui.draggable.offset();
var left_end = drop_p.left - drag_p.left;
var top_end = drop_p.top - drag_p.top;
ui.draggable.animate({
top: '+=' + top_end,
left: '+=' + left_end
});
ui.draggable.addClass('dropped');
ui.draggable.data('droppedin', $(this));
$(this).droppable('disable');
}
});
$(".snap").on("drop", function(event, ui) {
MyVar = event.target.getAttribute('id');
beh[MyVar] = ui.draggable.attr('id');
ui.draggable.attr('data-dropped-Id', $(this).attr('id'));
alert(beh[MyVar] + " " + MyVar);
});
.col-letter {
display: inline-block;
border: 1px solid #ccc;
background: #eee;
margin: 10px 0;
transition: background ease-In .2s;
}
.col-word.snap {
display: inline-block;
border: 1px solid #000;
background: #C5C5C5;
}
.dropped p {
background: #CDDC39 !important;
}
.dropped {
border-color: #000 !important;
}
.col-word.snap p {
margin: 0;
padding: 5px;
width: 30px;
height: 30px;
text-align: center;
line-height: 1.5;
}
.col-letter p {
margin: 0;
padding: 5px;
width: 30px;
height: 30px;
text-align: center;
line-height: 1.5;
cursor: move;
}
<link href="https://code.jquery.com/ui/1.11.4/themes/black-tie/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<div id="0" class='col-word'>
<p class="letters">c</p>
</div>
<div id="1" class='col-word snap' style="">
<p class="letters">__</p>
</div>
<div id="2" class='col-word snap' style="">
<p class="letters">__</p>
</div>
<div id="comparison">
<div id="v" class='col-letter'>
<p class="letters">v</p>
</div>
<div id="p" class='col-letter'>
<p class="letters">p</p>
</div>
<div id="u" class='col-letter'>
<p class="letters">u</p>
</div>
</div>
Hope this helps..:)
The following will get you the id of both the dragged element and dropped element..
$(".snap").on("drop", function(event, ui) {
MyVar = $(this).attr('id');
beh[MyVar] = ui.helper.attr('id');
alert(MyVar + " " + beh[MyVar]);
});
Same goes with your drag function use
MyVar = $(this).attr('id'); //to get your id
Fiddle
https://jsfiddle.net/2a6tur6w/3/
You are after event.target in your 'drop' handler...
$(".snap").on("drop", function(event, ui) {
MyVar = $(event.target).attr('id'); // here
beh[MyVar] = ui.draggable.attr('id');
alert(beh[MyVar] + " " + MyVar);
});
fiddle: https://jsfiddle.net/zoa3wL0n/
Why can't you store the value with the onclick handler and then retrieve it when you 'drop'?
var draggedItem
$(".snap").on("drag", function(event, ui) {
draggedItem = $(this).attr('id');
});
$(".snap").on("drop", function(event, ui) {
alert(draggedItem)
});
I want to automatically adjust the number list that was created using .append(). Example, if there are 4 items added on the list which will numbered from 2-4 respectively and if I removed item number 3, the item number 4 will automatically be number 3 and if I add a new item, it will be the last on the list. Here's my code below.
$('#display').click(function() {
$('#show').show();
});
var c = 1;
$('#append').click(function() {
var cnt = $('.cnt').val();
for (var i = 0; i < cnt; i++) {
c++;
$('#inputs').append("<div id='inputs' name='" + c + "'>" + c + ".)<button id='remove' name='" + c + "'>X</button></div>");
}
});
$(document).on('click', '#inputs #remove', function() {
var nm = $(this).attr('name');
$('div[name="' + nm + '"]').remove();
c--;
});
#show {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<button id='display'>Display</button>
<div id='show'>
<br>
<input type='text' class='cnt' value='1' placeholder="num of append" />
<button id='append'>+</button>
<br>
<div id='inputs'>
1.)
</div>
</div>
Here is the jsfiddle of the code.
here is your answer
Fiddle Here
$('#display').click(function() {
$('#show').show();
});
var c = 1;
$('#append').click(function() {
var cnt = $('.cnt').val();
for (var i = 0; i < cnt; i++) {
c++;
$('#inputs').append("<div class='inputs' name='" + c + "'><span class='number'>" +c + "</span>.)<button class='remove' name='" + c + "'>X</button></div>");
}
});
$(document).on('click', '#inputs .remove', function() {
var nm = $(this).attr('name');
$('div[name="' + nm + '"]').remove();
c--;
resetCount();
});
function resetCount(){
$('#inputs div.inputs').each(function(i){
$('.number', $(this)).text(i+2);
$('input', $(this)).attr('name', i+2);
});
}
#remain,
#total {
background-color: #333;
width: 60px;
height: 20px;
color: #fff;
padding: 0 10px;
}
input:focus {
background-color: #000;
color: #fff;
}
input {
background-color: #ccc;
}
#show {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id='display'>Display</button>
<div id='show'>
<br>
<input type='text' class='cnt' value='1' placeholder="num of append" />
<button id='append'>+</button>
<br>
<div id='inputs'>
1.)
</div>
</div>
You should not be using the same ID for different elements
Also the way you could do this is by creating a function that resets the elements counting after each add/delete event
When creating and appending elements in jQuery its better to use this syntax:
$('<ELEMENT TAG/>',{
ATTRIBUTE: VALUE
});
When looping through elements in jQuery its better to use $.each
$('#append').on('click', function(){
$('<div/>', {
'class': 'inputs',
html: '<span class="count"></span><input type="text" class="time" name="0" value="00:00:00"/><button>X</button>'
}).appendTo('#inputs');
resetInputsCount();
});
$('#inputs').on('click', '.inputs button', function(){
var $this = $(this);
$this.parent().remove();
resetInputsCount();
});
//The function that resets the count span text and the name value based on the current count of elements
function resetInputsCount(){
//looping through elements
$('#inputs div.inputs').each(function(i){
//caching the current element in a var named $this
var $this = $(this);
//changing the count span text to i+2 the 2 is added because the index starts at 0 and there is already one element 1.)
$('.count', this).text((i+2) + '.) ');
//change the value of the input name
$('input', $this).attr('name', i+2);
});
}
Demo on JSFiddle
I know theres an answer already but since I did the work I might as well post it.
Here's the fiddle for the example
here's the code:
Html
<div id='button'>
<span>Add</span>
</div>
<div id='content'></div>
CSS
#button span {
padding: 5px 15px;
background: #ccc;
cursor: pointer;
}
#button {
margin: 5px 0;
}
.delete {
cursor: pointer;
padding: 0 5px;
border: 1px solid gray;
}
jQuery
$(document).ready(function() {
var index = 1;
$('#button').on('click', function() {
var add = '<div class="new"><span class="number">' + index + '</span><input type="text"/><span class="delete">x</span></div>';
$('#content').append(add);
index++;
});
$(document).on('click', '.delete', function() {
index--;
$(this).parent().remove();
var index2 = 1;
var newelement = $('.new');
$(newelement).each(function() {
$(this).find('.number').text(index2);
index2++;
});
});
});
Using your html structure and adding some input fields (to be sure we maintain values)
Here is my approach:
(Also fixed duplicate id and names you have)
$('#display').click(function() {
$('#show').show();
});
var c = 1;
var inputs = [];
$('#append').click(function() {
var cnt = $('.cnt').val();
for (var i=0; i<cnt; i++) {
c++;
$div = $("<div id='input"+c+"' />").data('index', c);
$span = $("<span />").text(c+".)");
$button = $("<button class='input_remove' />").text("X");
$input = $("<input type='text' class='small' />").attr("name","input"+c);
$div.append($div).append($span).append($input).append($button);
$('#inputs').append($div);
}
});
$(document).on('click', '.input_remove', function() {
index = $(this).parent().data('index');
$("#inputs").find('#input'+index).remove();
c = 1;
$("#inputs").find('div').each(function(index,ele){
c++;
$(ele).attr('id',"input"+c).data('index',c)
.find("span").text(c+".)").end()
.find("input").attr("name","input"+c);
});
});
#show {
display: none;
}
.small { width:100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<button id='display'>Display</button>
<div id='show'>
<br>
<input type='text' class='cnt' value='1' placeholder="num of append" />
<button id='append'>+</button>
<br>
<div id='inputs'>
1.)
</div>
</div>
I am working on a project in which i had to store the the 3ID's of drop item in 3 textbox. but when i dragg and drop either one it stores it's id but when i drop the second item it stores it's ID but remove the ID of first from the textbox.
code
function dropItems(idOfDraggedItem, targetId, x, y) {
var targetObj = document.getElementById(targetId);
var subDivs = targetObj.getElementsByTagName('DIV');
if(subDivs.length>0 && targetId!='body')return;
var sourceObj = document.getElementById(idOfDraggedItem);
var numericIdTarget = targetId.replace(/[^0-9]/gi,'')/1;
var numericIdSource = idOfDraggedItem.replace(/[^0-9]/gi,'')/1;
if (numericIdTarget == '101') {
document.getElementById('txt1').value = numericIdSource;
} else {
document.getElementById('txt1').value = "";
}
if (numericIdTarget == '102') {
document.getElementById('txt2').value = numericIdSource;
} else {
document.getElementById('txt2').value = "";
}
if (numericIdTarget == '103') {
document.getElementById('txt3').value = numericIdSource;
} else {
document.getElementById('txt3').value = "";
}
var fn = "Feeling1:-" + document.getElementById('txt1').value + ", Feeling2:-" + document.getElementById('txt2').value + ", Feeling3:-" + document.getElementById('txt3').value + "";
document.getElementById('txt4').value = fn;
if (numericIdTarget - numericIdSource == 100) {
sourceObj.style.backgroundColor = '';
} else {
sourceObj.style.backgroundColor = '';
}
if (targetId == 'body') {
targetObj = targetObj.getElementsByTagName('DIV')[0];
}
targetObj.appendChild(sourceObj);
}
Initialization (from comments)
$(document).ready(function(e) {
var inp1=$("#txt1");
var inp2=$("#txt2");
var inp3=$("#txt3");
$("#bttn").click(function(){
if(inp1.val()=="" && (inp2.val()!="" || inp3.val()!="")) {
alert("Provide answer in consecutive manner");
} else if((inp1.val()=="" || inp2.val()=="") && inp3.val()!="" ) {
alert("Provide answer in consecutive manner");
} else {
alert("Submit");
}
});
})
I like to use jquery's built in draggable/droppable to acquire id's maybe this will help you with your current situation.
<!DOCTYPE HTML>
<html>
<head>
<title>Test Page</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( ".draggable" ).draggable();
$( ".droppable" ).droppable({
drop: function( event, ui ) {
var id = $( this ).attr("id");
var container = ui.draggable.attr("id");
alert(id + " " + container);
}
});
});
</script>
<style>
.draggable{
width: 100px;
height: 50px;
border: 1px black solid;
margin: 0.5em;
}
.droppable{
width: 100px;
height: 50px;
border: 1px black solid;
margin: 0.5em;
}
</style>
</head>
<body>
<div id="draggable1" class="draggable">
<p>Drag me to my target</p>
</div>
<div id="draggable2" class="draggable">
<p>Drag me to my target</p>
</div>
<div id="draggable3" class="draggable">
<p>Drag me to my target</p>
</div>
<div style="height: 25px;"></div>
<div id="droppable1" class="droppable">
<p>Drop here</p>
</div>
<div id="droppable2" class="droppable">
<p>Drop here</p>
</div>
</body>
</html>