How to target individual div & apply class or attribute id - javascript

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>

Related

JavaScript Get Selected Item's TextContent

I want to make a program that write out the textContent of the item that has clicked. For some reason this program only get the last element's content. Any idea what should I change inside the for loop?
var emailname = document.querySelectorAll(".name");
var gSenderName = document.getElementById('sname');
$('.name').click(function() {
for (var i = 0; i < emailname.length; i++) {
const sendername = emailname[i].textContent;
gSenderName.textContent = sendername;
}
});
.name:hover {
text-decoration: underline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>
<div>Selected:
<div id="sname"></div>
</div>
You do not need the loop here at all. You can simply get the currently clicked element's text by using this object. I will also suggest you not mix up vanilla JS and jQuery unnecessarily:
var gSenderName = $('#sname');
$('.name').click(function(){
gSenderName.text($(this).text());
});
.name:hover {
text-decoration: underline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>
<div>Selected:
<div id="sname"></div>
</div>
The loop runs and sets the text content of each item one after the other. Because each override the other, you always get the last one.
Just set the text content of the element that was clicked:
var gSenderName = document.getElementById('sname');
$('.name').click(e => {
gSenderName.textContent = e.target.textContent;
});
.name:hover {
text-decoration: underline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>
<div>Selected:
<div id="sname"></div>
</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>

Tie children of one div to children of another div with jquery

I have two parent divs: .inputs and .infoBoxes. Each of them have an equal number of children. When the user clicks into the first .input in .inputs, the first .infoBox in .infoBoxes should slideDown(). Same for second, third, etc. I'd like to do this without re-writing the same code for each pair. So far I have:
var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();
for(var i = 0; i < $inputs.length; i++ ) {
$($inputs[i]).find('.input').focus(function() {
$($infoBoxes[i]).slideDown();
})
$($inputs[i]).find('.input').blur(function() {
$($infoBoxes[i]).slideUp();
})
}
This isn't working but I have tried replacing i with the indexes of each div.
$($inputs[0]).find('.input').focus(function() {
$($infoBoxes[0]).slideDown();
})
$($inputs[0]).find('.input').blur(function() {
$($infoBoxes[0]).slideUp();
})
repeat...
repeat...
repeat...
This works but isn't very DRY. I'm looking for a better solution that won't have me repeating a bunch of code.
First code will not work, because you using same variable for all internal functions. You should wrap it into function, which will create local variable for index. Try following code:
var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();
for(var i = 0; i < $inputs.length; i++ ) {
(function(ix) {
$($inputs[ix]).find('.input').focus(function() {
$($infoBoxes[ix]).slideDown();
})
$($inputs[ix]).find('.input').blur(function() {
$($infoBoxes[ix]).slideUp();
})
})(i);
}
slideDown is used for showing elements. I am guessing you want to hide elements, since you are clicking on them and you cant click an hidden element. Use hide or slideUp to hide elements.
$(".input, .infobox").on("click", function() {
var ind = $(this).index();
$(".infobox:eq(" + ind + "), .input:eq(" + ind + ")").hide(500);
});
.input,
.infobox {
widht: 100%;
height: 50px;
text-align: center;
margin: 5px 0;
color: white;
}
.input {
background: red;
}
.infobox {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs">
<div class="input">1</div>
<div class="input">2</div>
<div class="input">3</div>
<div class="input">4</div>
<div class="input">5</div>
</div>
<div class="infoboxes">
<div class="infobox">1</div>
<div class="infobox">2</div>
<div class="infobox">3</div>
<div class="infobox">4</div>
<div class="infobox">5</div>
</div>

jQuery Array is not being removed on second click

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

Make div in div clickable with Javascript

Have a problem and can't get to solve it. Tried to use QuerySelectorAll and comma separating with GetElementsByClassName, but that didn't work, so I am wondering how to solve this problem.
I have this HTML:
<div class="area">Test title
<div class="some content" style="display: none">blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
<div class="area">
Test title
<div class="some content">
blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
JS:
function areaCollapse() {
var next = this.querySelector(".content");
if (this.classList.contains("open")) {
next.style.display = "none";
this.classList.remove("open");
} else {
next.style.display = "block";
this.classList.add("open");
}
}
var classname = document.getElementsByClassName("area");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', areaCollapse, true);
}
http://jsfiddle.net/1BJK903/nb1ao39k/6/
CSS:
.two {
position: absolute;
top: 0;
}
So now, the div with classname "area" is clickable. I positioned the div with class "two" absolute and now the whole div is clickable, except where this other div is. If you click on the div with classname "two", it doesn't work (it does not collapse or open the contents). How can I make this work, without changing the structure?
One way is using a global handler, where you can handle more than one item by checking its id or class or some other property or attribute.
Below snippet finds the "area" div and pass it as a param to the areaCollapse function. It also check so it is only the two or the area div (colored lime/yellow) that was clicked before calling the areaCollapse.
Also the original code didn't have the "open" class already added to it (the second div group), which mean one need to click twice, so I change the areaCollapse function to check for the display property instead.
function areaCollapse(elem) {
var next = elem.querySelector(".content");
if (next.style.display != "none") {
next.style.display = "none";
} else {
next.style.display = "block";
}
}
window.addEventListener('click', function(e) {
//temp alert to check which element were clicked
//alert(e.target.className);
if (hasClass(e.target,"area")) {
areaCollapse(e.target);
} else {
//delete next line if all children are clickable
if (hasClass(e.target,"two")) {
var el = e.target;
while ((el = el.parentElement) && !hasClass(el,"area"));
if (targetInParent(e.target,el)) {
areaCollapse(el);
}
//delete next line if all children are clickable
}
}
});
function hasClass(elm,cln) {
return (" " + elm.className + " " ).indexOf( " "+cln+" " ) > -1;
}
function targetInParent(trg,pnt) {
return (trg === pnt) ? false : pnt.contains(trg);
}
.area {
background-color: lime;
}
.two {
background-color: yellow;
}
.area:hover, .two:hover {
background-color: green;
}
.some {
background-color: white;
}
.some:hover {
background-color: white;
}
<div class="area">Test title clickable 1
<div class="some content" style="display: none">blablbala NOT clickable 1
</div>
<div class="two">This should be clickable too 1</div>
</div>
<div class="area">Test title clickable 2
<div class="some content">blablbala NOT clickable 2
</div>
<div class="two">This should be clickable too 2</div>
</div>
<div class="other">This should NOT be clickable</div>
You need to find your two elements while you're binding classname, and bind that as well.
var classname = document.getElementsByClassName("area");
for(var i=0; i < classname.length; i++){
classname[i].addEventListener('click', areaCollapse, true);
var twoEl = classname[i].getElementsByClassName("two")[0];
twoEl.addEventListener('click', function(e) { console.log('two clicked'); });
}
If you want to use jQuery:
$('.two').click(function(){
//action here
});

Categories

Resources