I have this code below that consists of three different array Red Fruits, Green Fruits and Suggested Fruits I am able to splice and push a single array value from Suggested Fruits to Green Fruits by clicking of the value and vice versa. But now i'm trying to do something different which is using my new Multidimensional Array: fruits to splice and push the value of the suggestFruits array to my red and green fruits array depending on the type e.g. type:1 goes to red fruits table and type:2 goes to green fruits table is there any easy way to accomplish this? Any help would be greatly appreciated!
var red = {};
var green = {};
var random = {};
var fruits = [];
var fruits1 = {["fruit"]:"Apple", ["type"]:"1"}
var fruits2 = {["fruit"]:"Tomato", ["type"]:"1"}
var fruits3 = {["fruit"]:"Lime", ["type"]:"2"}
var fruits4 = {["fruit"]:"Guava", ["type"]:"2"}
fruits.push(fruits1,fruits2,fruits3,fruits4);
console.log(fruits);
var suggestFruits = fruits.filter(x => x.fruit).map(x => x.fruit);
console.log(suggestFruits);
var key = "Red Fruits";
red[key] = ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'];
var key2 = "Green Fruits";
green[key2] = ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'];
var key3 = "Random Fruits";
random[key3] = suggestFruits;
function redraw() {
var redString = '';
$.each(red[key], function(index) {
redString += ('<div class="pilldiv redpill class">' + red[key][index] + '</div>');
});
$('.redclass').html(redString);
var greenString = '';
$.each(green[key2], function(index) {
greenString += ('<div class="pilldiv greenpill class">' + green[key2][index] + '</div>');
});
$('.greenclass').html(greenString);
var randomString = '';
$.each(random[key3], function(index) {
randomString += ('<div class="pilldiv randompill class">' + random[key3][index] + '</div>');
});
$('.randomclass').html(randomString);
}
function listener() {
$(document).ready(function() {
$(document).on("click", "#randomid div", function() {
data = this.innerHTML;
k1 = Object.keys(random).find(k => random[k].indexOf(data) >= 0)
index = random[k1].indexOf(data);
random[k1].splice(index, 1);
green[key2].push(data);
$(".total_count_Green_Fruits").html(key2 + ': ' + green[key2].length);
var element = $(this).detach();
$('#greenid').append('<div class="new-green-fruit pilldiv class ">' + element.html() + '</div>');
});
});
$('body').on('click', 'div.new-green-fruit', function() {
data2 = this.innerHTML;
console.log(data2);
k2 = Object.keys(green).find(k => green[k].indexOf(data2) >= 0)
index2 = green[k2].indexOf(data2);
green[k2].splice(index2, 1);
random[key3].push(data2);
$(this).detach();
var element2 = $(this).detach();
$('#randomid').append('<div class="pilldiv randompill class" >' + element2.html() + '</div>');
});
}
redraw();
listener();
.pilldiv {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
color: Black;
margin: 2px;
}
.redpill {
background-color: Pink;
cursor:default;
}
.greenpill {
background-color: SpringGreen;
cursor:default;
}
.randompill {
background-color: LightBlue;
cursor:pointer;
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center;
}
.wrappingflexbox {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.top {
margin-bottom: 20px
}
h3{
font-weight: normal;
}
.panel {
display: table;
height: 100%;
width: 60%;
background-color:white;
border: 1px solid black;
margin-left: auto;
margin-right: auto;
}
.new-green-fruit{
background-color: LightBlue;
cursor:pointer;
}
.top{
margin-bottom:30px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div class="panel">
<div style="float:left;width:calc(50% - 5px);">
<h3 class="class center">Red Fruits</h3>
<div id="redid" class="redclass wrappingflexbox top"></div>
</div>
<div style="float:right;width:calc(50% - 5px)">
<h3 class="class center">Green Fruits</h3>
<div id="greenid" class="greenclass wrappingflexbox top"></div>
</div>
<div style="clear:both">
<h3 class="center class">Suggested Fruits</h3>
<div id="randomid" class="randomclass wrappingflexbox top"></div>
</div>
</div>
</body>
</html>
There's a lot going on in this question, but from what I gathered, you are simply trying to push the names of the fruits that are type === "1" to the red fruits array, and type === "2" to the green fruits array.
Your main issue with splitting the suggestedFruits into the red and green categories is that when you create the suggestedFruits array, you are losing the type information. What you can do, though, is you can look back at the original fruits array to get the info.
Here's how you can accomplish that:
var fruits = [
{fruit:"Apple", type:"1"},
{fruit:"Tomato", type:"1"},
{fruit:"Lime", type:"2"},
{fruit:"Guava", type:"2"},
];
// map so we can know how to map fruit.type into the correct fruitTypes array
var fruitTypeMap = {"1": "Red Fruits", "2": "Green Fruits"}
// one container for all fruit types so we can access dynamically
var fruitTypes = {
"Red Fruits": ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'],
"Green Fruits": ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'],
"Random Fruits": fruits.map(fruit => fruit.fruit)
};
// clone element for easily creating fruit-pills
var clonePill = $(".clone");
// initialize the red/green/random pills
Object.keys(fruitTypes).forEach(key => {
fruitTypes[key].forEach(fruit => {
var $newFruit = clonePill.clone();
// remove clone class so it is visible and doesn't get re-cloned
$newFruit.removeClass("clone");
// set the text
$newFruit.text(fruit);
// append to the correct list in DOM
$(`[data-fruits="${key}"]`).append($newFruit);
});
});
// handler for moving a fruits back and forth
function moveFruit (e) {
// get the category from the data-fruits property on the parent container
var fruitCategory = $(this).parent().data("fruits");
var fruitName = $(this).text();
// detach the fruit element from the DOM and keep it in a variable so we can re-insert later
var $fruit = $(this).detach();
if (fruitCategory === "Random Fruits") {
// get the type number from the original fruits array
var fruitType = fruits.find(fruit => fruit.fruit === fruitName).type;
// find the correct array to place the fruit into
var fruitArr = fruitTypes[fruitTypeMap[fruitType]];
// find the index of the array it is currently in
var fruitIndex = fruitTypes["Random Fruits"].indexOf(fruitName);
// splice out of current array and insert into destination array in 1 line
fruitArr.push(fruitTypes["Random Fruits"].splice(fruitIndex, 1)[0]);
// add movable class so we can toggle it back to Random Fruits on click
$fruit.addClass("movable");
// finally, add to the correct list in the DOM
$(`[data-fruits="${fruitTypeMap[fruitType]}"]`).append($fruit);
}
else {
// find the current array
var fruitArr = fruitTypes[fruitCategory];
// find the index of the fruit in the current array
var fruitIndex = fruitArr.indexOf(fruitName);
// splice out of current array and insert into destination array in 1 line
fruitTypes["Random Fruits"].push(fruitArr.splice(fruitIndex, 1)[0]);
// add back to Random Fruits list
$('[data-fruits="Random Fruits"]').append($fruit);
}
}
// handle click on all fruits that we label as .movable in the red/green lists
$(".red-fruits, .green-fruits").on("click", ".movable", moveFruit);
// handle click on all items in Random Fruits list
$(".random-fruits").on("click", ".fruit-pill", moveFruit);
.clone {
display: none;
}
.fruit-pill {
border-radius: 20px;
padding: 10px 15px;
display: inline-block;
}
.movable {
cursor: pointer;
}
.red-fruits > .fruit-pill {
background-color: rgba(255, 0, 0, 0.6);
}
.red-fruits > .movable {
background-color: rgb(255, 150, 150);
}
.green-fruits > .fruit-pill {
background-color: rgba(0, 255, 0, 0.7);
}
.green-fruits > .movable {
background-color: rgb(200, 255, 175);
}
.random-fruits > .fruit-pill {
background-color: rgba(0, 0, 0, 0.2);
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fruits-container">
<div class="red-fruits" data-fruits="Red Fruits">
</div>
<div class="green-fruits" data-fruits="Green Fruits">
</div>
<div class="random-fruits" data-fruits="Random Fruits">
</div>
</div>
<div class="fruit-pill clone"></div>
Related
I am making a javascript shopping cart. When you click on an item, the contents of that item are appended on the DOM via javascript. Having some difficulty with my code, specifically the sections where I bolded with '** **'
For my 'dropDown-amount' class, I have a number as the value but i cant seem to access that value later on in the code (see dropDown-price).
Also I have a For statement on my if/else statement that tries to loop through each index in 'items' array and to essentially count how many times one specific item is inside the list (so I can update quantity of x item on DOM) but having trouble getting everything to work. I know what I have to do to solve this problem and I know all 3 of these issues are linked together, just don't know what is exactly causing this to fail.
//dropdown menu hidden
const cartDropdown = document.querySelector('.cart-dropDown-items');
//every single + symbol
const addToCartButtons = document.querySelectorAll('.addToCart');
//price of item
const foodPrices = document.querySelectorAll('.selection-row-title');
//name of item
const foodNames = document.querySelectorAll('.selection-row-foodName');
//weight of item
const foodWeights = document.querySelectorAll('.selection-row-weight');
const items = [];
let total = 0;
for (let i = 0; i < addToCartButtons.length; i++) {
addToCartButtons[i].addEventListener('click', function() {
const newItem = document.createElement('div');
newItem.className = 'dropDown-item';
let amountItems = document.querySelector('.amount-items');
newItem.innerHTML =
`<div class='dropDown-title dropDown-info'>
${foodNames[i].innerHTML}
</div>
<div class='dropDown-amount dropDown-info'>
**<p class='amount-items'>${1}</p>**
</div>
<div class='dropDown-price dropDown-info'>
**${Number(foodPrices[i].innerHTML.substring(1)) * Number(amountItems.textContent)}**
</div>`;
console.log(newItem)
// if item currently exists in array, just update amount in checkout and increase count++
if (items.includes(addToCartButtons[i].value)) {
items.push(addToCartButtons[i].value); **
for (let i = 0; i < items.length; i++) {
if (items[i].includes(addToCartButtons[i].value)) {
Number(amountItems.innerHTML) + 1;
}
} **
}
// if items does not exist in array, update dom with new item UI and count = 1 by default
else {
items.push(addToCartButtons[i].value);
cartDropdown.appendChild(newItem);
}
console.log(items)
})
}
.cart-dropDown-items {}
.dropDown-title {}
.dropDown-item {
display: flex;
align-items: center;
text-align: center;
background-color: orange;
margin: 3px;
padding: 4px;
}
.dropDown-info {}
.dropDown-title {
width: 40%;
}
.dropDown-amount {
width: 30%;
text-align: center;
}
.dropDown-amount p {
border: 1px solid black;
width: 35%;
padding: 8px;
margin: 0 auto;
background-color: white;
}
.dropDown-price {
width: 30%;
}
<!--cart dropDown-->
<div class='cart-dropDown'>
<div class='cart-dropDown-header'>
<p>My Carts</p>
<p>Personal Cart</p>
<p class='cart-dropDown-close'>Close</p>
</div>
<div class='cart-dropDown-items'>
<!--
<div class='dropDown-item'>
<div class='dropDown-title dropDown-info'>Mixed bell pepper, 6 ct</div>
<div class='dropDown-amount dropDown-info'>1</div>
<div class='dropDown-price dropDown-info'>$9.84</div>
</div>
next unique item...
-->
</div>
<div class='cart-dropDown-checkout'>
<div class='cart-dropDown-checkout1'>
<p>Go to Checkout</p>
</div>
<div class='cart-dropDown-checkout2'>
<p>$0</p>
</div>
</div>
</div>
</div>
The problem is when duplicate multiple div but with different data-type, it still running a same content, i want correct all div will have the different content following the different data-type.
Is there a way to do this?
$(function() {
// document
'use strict';
var cp = $('div.box');
// unique id
var idCp = 0;
for (var i = 0; i < cp.length; i++) {
idCp++;
cp[i].id = "cp_" + idCp;
}
// diffrent type
if (cp.data('type') == "c1") {
cp.addClass('red').css({
"background: 'red',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c1-title' + '</div>');
} else if (cp.data('type') == "c2") {
cp.addClass('green').css({
"background": 'green',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c2-title' + '</div>');
} else {
return false;
}
}); //end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<! it should be like this>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c2 title</div>
</div>
<! currently wrong output>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c1 title</div>
</div>
The problem in your code is that you are not looping inside the div's. You have to use the .each() function while looping inside all the elements
$(function() {
var cp = $('div.box');
cp.each(function() {
var _cp = $(this);
var text = _cp.attr("data-type") + "-title"; //Generate the text dynamically
var cls = _cp.attr("data-class"); //Get the class dynamically
_cp.addClass(cls).append('<div class="cp-title">' + text + '</div>'); //Add the class and append the text to the parent div
});
}); //end
.box{
padding: 20px;
display: table;
}
.red{
background: red;
}
.green{
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1" data-class="red"></div>
<div class="box" data-type="c2" data-class="green"></div>
Probably you're searching for something like this.
// document.ready
$(function() {
'use strict';
$('.box').each(function(i,elem){
var ref = +$(elem).attr("data-type").match(/\d/)[0], addClass = 'default';
switch(true) {
case ref === 1:
addClass = 'red';
break;
case ref === 2:
addClass = 'green';
break;
}
$(this)
.addClass(addClass)
.append('<div class="cp-title">c'+ref+' title</div>');
});
}); //end
.red{
background: red;
padding: 20px;
display: table;
}.green{
background: green;
padding: 20px;
display: table;
}.default {
background: #2d2d2d;
color: #f6f6f6;
padding: 20px;
display: table;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1"></div><div class="box" data-type="c2"></div>
I have a page like below image
According to my requirement, user is allowed to enter digits from the keypad that is provided on the page only. So input field is readonly.
Now I am trying to get is, when user start entering month then other text should remain in text field until user types that. e.g. 05/DD/YYYY like this. And accordingly that text will be hide.
If I placed placeholder then when user starts entering digits all text gone. I don't want that. So I have taken "MM/DD/YYYY" text in seperate span tag.
var Memory = "0", // initialise memory variable
Current = "", // and value of Display ("current" value)
Operation = 0, // Records code for eg * / etc.
MAXLENGTH = 8; // maximum number of digits before decimal!
function format(input, format, sep) {
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
function AddDigit(dig) { //ADD A DIGIT TO DISPLAY (keep as 'Current')
if (Current.indexOf("!") == -1) { //if not already an error
if ((eval(Current) == undefined) &&
(Current.indexOf(".") == -1)) {
Current = dig;
document.calc.display.focus();
} else {
Current = Current + dig;
document.calc.display.focus();
}
Current = Current.toLowerCase(); //FORCE LOWER CASE
} else {
Current = "Hint! Press 'Clear'"; //Help out, if error present.
}
if (Current.length > 0) {
Current = Current.replace(/\D/g, "");
Current = format(Current, [2, 2, 4], "/");
}
document.calc.display.value = Current.substring(0, 10);
document.getElementById("cursor").style.visibility = "hidden";
}
function Clear() { //CLEAR ENTRY
Current = "";
document.calc.display.value = Current;
document.calc.display.focus();
document.getElementById("cursor").style.visibility = "visible";
//setInterval ("cursorAnimation()", 5000);
}
function backspace() {
Current = document.calc.display.value;
var num = Current;
Current = num.slice(0,num.length - 1);
document.calc.display.value = Current;
document.calc.display.focus();
document.getElementById("cursor").style.visibility = "hidden";
}
function cursorAnimation() {
$("#cursor").animate({
opacity: 0
}, "fast", "swing").animate({
opacity: 1
}, "fast", "swing");
}
//--------------------------------------------------------------->
$(document).ready(function() {
document.getElementById("cursor").style.visibility = "visible";
//setInterval ("cursorAnimation()", 1000);
});
.intxt1 {
padding: 16px;
border-radius: 3px;
/* border: 0; */
width: 1017px;
border: 1px solid #000;
font-family: Droid Sans Mono;
background: #fff;
}
.txtplaceholder {
font-family: "Droid Sans Mono";
color: #D7D7D7;
position: relative;
float: left;
left: 219px;
top: 17px;
z-index: 10 !important;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
display: inline-block;
}
#cursor {
position: relative;
z-index: 1;
left: 32px;
top: 2px;
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form Name="calc" method="post">
<div style="position:relative">
<span id="cursor">_</span>
<span class="txtplaceholder">MM/DD/YYYY</span>
<span style="z-index:100">
<input class="intxt1" autocomplete="off" id="pt_dob" name="display" value="" type="text" readonly>
</span>
<button class="cancel-icon" type="reset" onClick="Clear()"></button>
</div>
<div class="num_keypad1" style=" margin-top:19px;">
<!-- Screen and clear key -->
<div class="num_keys">
<!-- operators and other keys -->
<span id="key1" onClick="AddDigit('1')">1</span>
<span id="key2" onClick="AddDigit('2')">2</span>
<span id="key3" onClick="AddDigit('3')">3</span>
<span id="key4" onClick="AddDigit('4')">4</span>
<span id="key5" onClick="AddDigit('5')">5</span>
<span id="key6" onClick="AddDigit('6')">6</span>
<span id="key7" onClick="AddDigit('7')">7</span>
<span id="key8" onClick="AddDigit('8')">8</span>
<span id="key9" onClick="AddDigit('9')">9</span>
<span id="key0" onClick="AddDigit('0')" style="width: 200px;">0</span>
<span id="keyback" class="clear" onClick="backspace()"> <div class="num_xBox">X</div></span>
</div>
</div>
</form>
With the above Html code I am getting below result:
Problems coming are below:
My digits are going below the text "MM/DD/YYYY". I am not getting how should I get my digits above that text
How should I hide the text which is entered by user and display other accordingly e.g. "MM" should hide if user enters 05 and display other text like this "05/DD/YYYY".
Can anyone please help me in this?
NOTE: With input type=date or by any other plugins I can achieve above functionality but my requirement is different. I have to achieve this with HTML, CSS, JS only.
I would use a ready built data picker for this kind of thing as it would have all the error checking in built to ensure you enter a date in the correct format.
The way you are doing it, you are not able to check if the day is valid until you have entered the month, by which time the user will have to backspace and it will be a very slow and clunky process which is not very user friendly.
Anyway, if you persist with a number pad, here is how I would do it.
put the date in a global array
have a global index counter
add and remove values based on the index counter
The following is a very quick example of the above
var dateBits = ["D", "D", "M", "M", "Y", "Y", "Y", "Y"],
letters = ["D", "D", "M", "M", "Y", "Y", "Y", "Y"],
input = document.getElementById('pt_dob'),
currentIndex = 0;
function makeDate() {
return dateBits[0] + dateBits[1] + "/" + dateBits[2] + dateBits[3] + "/" + dateBits[4] + dateBits[5] + dateBits[6] + dateBits[7];
}
function AddDigit(number) {
dateBits[currentIndex] = number;
if (currentIndex < 8) {
currentIndex++;
}
input.value = makeDate();
}
function RemoveDigit() {
if (currentIndex > 0) {
currentIndex--;
}
dateBits[currentIndex] = letters[currentIndex];
input.value = makeDate();
}
function Clear() {
for (i = 0; i < letters.length; i++) {
dateBits[i] = letters[i];
}
currentIndex = 0;
input.value = makeDate();
}
input.value = makeDate(); // run this line onload or include this whole script at the bottom of the page to get your input to start with your text
.intxt1 {
padding: 16px;
border-radius: 3px;
/* border: 0; */
width: 1017px;
border: 1px solid #000;
font-family: Droid Sans Mono;
background: #fff;
}
#cursor {
position: relative;
z-index: 1;
left: 32px;
top: 2px;
visibility: hidden;
}
.num_keys > span {
display: inline-flex;
width: 2em;
height: 2em;
align-items: center;
justify-content: center;
cursor: pointer;
border: 1px solid black;
}
<form Name="calc" method="post">
<div style="position:relative"><span id="cursor">_</span>
<span class="txtplaceholder">MM/DD/YYYY</span><span style="z-index:100"><input class="intxt1" autocomplete="off" id="pt_dob" name="display" value="" type="text" autocomplete="off" readonly></span>
<button class="cancel-icon" type="reset" onClick="Clear(); return false;">clear</button>
</div>
<div class="num_keypad1" style=" margin-top:19px;">
<!-- Screen and clear key -->
<div class="num_keys">
<!-- operators and other keys -->
<span id="key1" onClick="AddDigit('1')">1</span>
<span id="key2" onClick="AddDigit('2')">2</span>
<span id="key3" onClick="AddDigit('3')">3</span>
<span id="key4" onClick="AddDigit('4')">4</span>
<span id="key5" onClick="AddDigit('5')">5</span>
<span id="key6" onClick="AddDigit('6')">6</span>
<span id="key7" onClick="AddDigit('7')">7</span>
<span id="key8" onClick="AddDigit('8')">8</span>
<span id="key9" onClick="AddDigit('9')">9</span>
<span id="key0" onClick="AddDigit('0')" style="width: 200px;">0</span>
<span id="keyback" class="clear" onClick="RemoveDigit()"> <div class="num_xBox">X</div></span>
</div>
</div>
</form>
var text = "DD/MM/YYYY";
$(".textbox").on("focus blur", function(){
$(".wrapper").toggleClass("focused");
});
$(".wrapper").click(function (e) {
if (e.target == this) {
var b = $(".textbox", this).focus();
}
}).trigger("click");
$(".wrapper > .textbox").on("input", function(){
var ipt = $(this).text().replace(/\u00A0/g, " ");
$(".gray").text(text.substr(ipt.length, text.length));
}).trigger("input");
check this fiddle http://jsfiddle.net/7sD2r/22/
If ive understood all well. I think the one solution is to store user input in hidden field. Then get this input to split digits and return to visible input value that consists of splitted values etc.
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(', '));
});
<!DOCTYPE HTML>
<html>
<head>
<title>HTML5 localStorage (name/value item pairs) demo</title>
<style >
td, th {
font-family: monospace;
padding: 4px;
background-color: #ccc;
}
#hoge {
border: 1px dotted blue;
padding: 6px;
background-color: #ccc;
margin-right: 50%;
}
#items_table {
border: 1px dotted blue;
padding: 6px;
margin-top: 12px;
margin-right: 50%;
}
#items_table h2 {
font-size: 18px;
margin-top: 0px;
font-family: sans-serif;
}
label {
vertical-align: top;
}
</style>
</head>
<body onload="doShowAll()">
<h1>HTML5 localStorage (name/value item pairs) demo</h1>
<form name=editor>
<div id="hoge">
<p>
<label>Value: <textarea name=data cols=41 rows=10></textarea></label>
</p>
<p>
<label>Name: <input name=name></label>
<input type=button value="getItem()" onclick="doGetItem()">
<input type=button value="setItem()" onclick="doSetItem()">
<input type=button value="removeItem()" onclick="doRemoveItem()">
</p>
</div>
<div id="items_table">
<h2>Items</h2>
<table id=pairs></table>
<p>
<label><input type=button value="clear()" onclick="doClear()"> <i>* clear() removes all items</i></label>
</p>
</div>
<script>
function doSetItem() {
var name = document.forms.editor.name.value;
var data = document.forms.editor.data.value;
var origData = localStorage.getItem(name) || 0;
localStorage.setItem(name, parseInt(origData) + parseInt(data));
doShowAll();
}
function doGetItem() {
var name = document.forms.editor.name.value;
document.forms.editor.data.value = localStorage.getItem(name);
doShowAll();
}
function doRemoveItem() {
var name = document.forms.editor.name.value;
document.forms.editor.data.value = localStorage.removeItem(name);
doShowAll();
}
function doClear() {
localStorage.clear();
doShowAll();
}
function doShowAll() {
var key = "";
var pairs = "<tr><th>Name</th><th>Value</th></tr>\n";
var i=0;
for (i=0; i<=localStorage.length-1; i++) {
key = localStorage.key(i);
pairs += "<tr><td>"+key+"</td>\n<td>"+localStorage.getItem(key)+"</td></tr>\n";
}
if (pairs == "<tr><th>Name</th><th>Value</th></tr>\n") {
pairs += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('pairs').innerHTML = pairs;
}
</script>
</form>
</body>
</html>
Hi friends,
I wants to locally save the data,now I am able to save the data locally by the code.even if I give the same name the value is getting added and saved locally.but the name should be shown in order of high value to low(example: Ram 20,Renu 18,green 2 like wise...).so how to do this?
function doSetItem() {
var name = document.forms.editor.name.value;
var data = document.forms.editor.data.value;
var origData = localStorage.getItem(name) || 0;
localStorage.setItem(name, parseInt(origData) + parseInt(data));
doShowAll();
}
To display them in descending order:
function doShowAll() {
var key = "";
var pairs = "<tr><th>Name</th><th>Value</th></tr>\n";
var userArray = [];
for (var i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
userArray.push({name:key, value:parseInt(localStorage.getItem(key))});
}
userArray.sort(function(a, b){
return b.value - a.value;
});
userArray.forEach(function(user){
pairs += "<tr><td>" + user.name + "</td>\n<td>" + user.value + "</td></tr>\n";
});
if (pairs === "<tr><th>Name</th><th>Value</th></tr>\n") {
pairs += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('pairs').innerHTML = pairs;
}
For what I can see in your code, you're just replacing the value, you need to get the existent value from the localStorage first, append to it the new one and then asign the result to the localStorage.