jQuery Array is not being removed on second click - javascript

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(', '));
});

Related

I was trying to make a to-do list using javascript but unable to append the selected option

Aim was to take input and create radio buttons and label dynamically like a list which when checked goes to bottom while label name coming from the input textfield that we write. I was able to do this with the radio button but not with the label. Please help me out I'm new here.
[Fiddle] (http://jsfiddle.net/wju6t7k3/2/)
<div id = "container" >
<div class="row">
<div class="col-12">
<input id = "txt" type = "text" placeholder="Add new.." >
<button id="btn" value = "add" type = "button" onClick = "add()" >
</button>
</div>
<div id="done" class="col-12">
</div>
</div> <!-- row -->
<script>
//js
var j = 0;
var textval="";
function getInputValue(){
// Selecting the input element and get its value
inputVal = document.getElementById("txt").value;
// Displaying the value
alert(inputVal);
}
function add() {
if (document.getElementById('txt').value != '') {
j++;
var title = document.getElementById('txt').value;
var node = document.createElement('div');
node.innerHTML = '<input type="checkbox" class="checkbox-round" id="check' + j + '" name="check' + j + '"><label for="check' + j + '">' + title + '</label>';
document.getElementById('done').appendChild(node);
}
}
input = document.getElementById("txt");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
document.getElementById("btn").click();
textval =this.value;
onfocus=this.value='';
}
});
function countChecked(event) {
alert(textval);
alert("balle");
getInputValue();
$(this).parent().parent().append(this).append('<label>textvalh</label>').append('<br>');
}
$("#container").on( "click", "input[type=checkbox]", countChecked );
function getForm(event) {
event.preventDefault();
var form = document.getElementById("task").value;
console.log(form);
}
</script>
You have to make a container or a parent element for the checkbox and its label to have more control of it.
and if you want to separate the checkbox that is checked, then make another div element to make a separation.
Here's an example, this is based on your code:
//js
var j = 0;
function add() {
if (document.getElementById('txt').value != '') {
j++;
var title = document.getElementById('txt').value;
var node = document.createElement('div');
node.innerHTML = '<div><input type="checkbox" class="checkbox-round" id="check' + j + '" name="check' + j + '"><label for="check' + j + '">' + title + '</label></div>';
document.getElementById('done').appendChild(node);
}
}
input = document.getElementById("txt");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
document.getElementById("btn").click();
textval = this.value;
this.value='';
}
});
function countChecked(event) {
const isChecked = event.currentTarget.checked;
// Get parent of checkbox which is the closest <div> element
const checkbox_parent = $(event.currentTarget).closest('div');
if (isChecked) // Move element to div with ID = selected
checkbox_parent.appendTo('#selected')
else // Move element to div with ID = done
checkbox_parent.appendTo('#done')
}
$('#container').on('change', 'input[type="checkbox"]', countChecked)
input, input:active{
border:none;
cursor: pointer;
outline: none;
}
::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: blue;
}
::-moz-placeholder { /* Firefox 19+ */
color: blue;
}
:-ms-input-placeholder { /* IE 10+ */
color: blue;
}
:-moz-placeholder { /* Firefox 18- */
color: blue;
}
button{
display:none;
}
.checkbox-round {
width: 1.3em;
height: 1.3em;
background-color: white;
border-radius: 50%;
vertical-align: middle;
border: 1px solid #ddd;
-webkit-appearance: none;
outline: none;
cursor: pointer;
}
.checkbox-round:checked {
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" >
<div class="row">
<div class="col-12" style="border: dashed red 3px;">
<input id = "txt" type="text" placeholder="Add new.." />
<button id="btn" value="add" type="button" onClick ="add()">Add</button>
<div id="done" class="col-12" style="border: solid purple 3px;">
</div>
<div id="selected" class="col-12" style="border: solid gray 3px;">
</div>
</div>
</div> <!-- row -->
</div>
Happy Coding!

JS splicing array value according to key value

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>

Create multiple divs with different content

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>

How to target individual div & apply class or attribute id

How can i select each div inside parent div & apply class (om_0 & go on) with increasing index number. Here I am unable to target each div.
Or how can I add attribute id="om_0", id="om_1", id="om_2" etc. to each div
The problem is it's applying all classes in one div & repeat it
var cirLength = $("div#circleBox > div").length;
for(var i=0; i<cirLength; i++){
$("div#circleBox").find('div').addClass('om_'+i);
}
<div id="circleBox"><div class="om_0 om_1 om_2"><span>AcessGreen</span></div><div class="om_0 om_1 om_2"><span>AccessBlue</span></div><div class="om_0 om_1 om_2"><span>AccessOrange</span></div></div>
You can use each() to iterate jQuery objects
$("div#circleBox").find('div').each(function(i) {
$(this).addClass('om_' + i);
// If you need to add it as id then use `this.id= 'om_' + i ` instead of `$(this).addClass('om_' + i)`
});
.om_0 {
color: red;
}
.om_1 {
color: green;
}
.om_2 {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="circleBox">
<div><span>AcessGreen</span>
</div>
<div><span>AccessBlue</span>
</div>
<div><span>AccessOrange</span>
</div>
</div>
With your own code you need to select individual item using eq()
var cirLength = $("div#circleBox > div").length;
for (var i = 0; i < cirLength; i++) {
$("div#circleBox").find('div').eq(i).addClass('om_' + i);
}
.om_0 {
color: red;
}
.om_1 {
color: green;
}
.om_2 {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="circleBox">
<div><span>AcessGreen</span>
</div>
<div><span>AccessBlue</span>
</div>
<div><span>AccessOrange</span>
</div>
</div>

jQuery how to auto adjust the number list when 1 of the list is removed?

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>

Categories

Resources