0

I would like to capture data from selected div(ie. name of country) by click and put in span , additionaly i want to find some way to mark selected divs, but also unmark others div which were selected previously.

https://codepen.io/tatasek/pen/PoojNGL

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="div div__first"></div>
    <div class="div div__second"></div>
    <div class="div div__third"></div>

    <p>I have selected:<span class="selectedCountry"></span></p>
    <script src="app.js"></script>
</body>
</html>

CSS

body{
    display: flex;
    height: 100vh;
    justify-content: center;
    align-items: center;;
}

.div{
    margin-left: 10px;
    padding: 3px;
    border: 2px solid black;
    background-color: skyblue;
    cursor: pointer;
}

p{
    margin-left: 10px;;
}
.active{
  background-color: yellow;
}

JS

const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');

divList.forEach(function(div, index){
    div.textContent = countries[index];

})

Thanks for your time! Michal

4 Answers4

0

Try

for (let i = 0; i < document.getElementsByClassName('div').length; i++) {
   document.getElementsByClassName('div')[i].addEventListener('click', appendToSpan, false);
}
function appendToSpan(e) {
   document.getElementsByClassName('selectedCountry')[0].innerText += e.target.innerText;
}

Edit:

Change to:

const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');

divList.forEach(function(div, index){
    div.textContent = countries[index];
    div.addEventListener('click', function() {
      this.classList.toggle('active');
      if (this.classList.contains('active')) {
         document.getElementsByClassName('selectedCountry')[0].classList.add(this.innerText);
      } else {
         document.getElementsByClassName('selectedCountry')[0].classList.remove(this.innerText);
      }
      let classes = document.getElementsByClassName('selectedCountry')[0].getAttribute('class').split(' ');
      document.getElementsByClassName('selectedCountry')[0].innerText = '';
      for (let i = 1; i < classes.length; i++) {
         document.getElementsByClassName('selectedCountry')[0].innerText += classes[i]
      }
    })
})
ezra
  • 307
  • 3
  • 13
  • Thanks, i works partaly ( it doesnt delete previously selected country and it is getting a little mess) but i will try to solve this problem. thanks btw do u have any solution for my second problem? – Michał Soja Oct 25 '19 at 22:41
  • yes it has been tested in codepen-- works perfectly – ezra Oct 25 '19 at 22:50
0

Building on what you've done so far, I just added some event listeners to check for changes and add the selected items to the list. Let me know if you need any further clarification.

const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');

divList.forEach(function(div, index){
div.textContent = countries[index];
div.addEventListener('click', function(){
  divList.forEach(function(el, i) {
    el.classList.remove('active')
  })
  this.classList.toggle('active');
})

})



var choices = document.getElementsByTagName('div')

for(var i = 0; i < choices.length; i++) {
  choices[i].addEventListener('click', function() {
     document.getElementsByClassName('selectedCountry')[0].innerText = 
document.getElementsByClassName('active')[0].innerText;



  })
}
body{
    display: flex;
    height: 100vh;
    justify-content: center;
    align-items: center;
}

.div{
    margin-left: 10px;
    padding: 15px;
    border: 2px solid black;
    background-color: skyblue;
    cursor: pointer;
}

p{
    margin-left: 10px;
}

.active{
  background-color: yellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="div div__first"></div>
    <div class="div div__second"></div>
    <div class="div div__third"></div>

    <p>I have selected:<span class="selectedCountry"></span></p>
    <script src="app.js"></script>
</body>
</html>
Max Jacobson
  • 312
  • 3
  • 12
  • 1
    Thanks for yoru help mate i will review this code tomorrow cuz im a little bit exhausted and i will let u know – Michał Soja Oct 25 '19 at 22:49
  • If you click on 'Run code snippet' you can see it in action without having to plug it in to your code. – Max Jacobson Oct 25 '19 at 22:50
  • Hey why did you put here attribute “i” in the bracekts? ` divList.forEach(function(el, i) { el.classList.remove('active') }) ` – Michał Soja Oct 26 '19 at 06:21
  • Hey, sorry, I just realized I had that in there. That isn't needed in this scenario. It's generally used to track the index of the iteration. I have a habit of adding it in case I ever need to use it. – Max Jacobson Oct 28 '19 at 19:46
0

I've used addEventListener on click event on each div. Also I've created selected variable which is an array and keeps selected items. On click I check if the selected value is in selected variable by indexOf() function which returns -1 if there is not. Then I push() value to the array if it's not selected yet or delete it by splice() and index of value. Array is printed by join() function which concats each value of array,

const divList = document.querySelectorAll('.div');
const output = document.querySelector('.selectedCountry');
const countries = ['Lithuania', 'Latvia', 'Estonia'];
let selected = [];

divList.forEach((div, index) => {
    div.textContent = countries[index];
    div.addEventListener('click',()=> {
      var indexOfDiv = selected.indexOf(countries[index]);
      (indexOfDiv >= 0) 
        ? (selected.splice(indexOfDiv,1) && div.classList.remove('selected'))
        : (selected.push(div.textContent) && div.classList.add('selected'))
      output.textContent = selected.join(', ');
    });
});
.div { border: 1px solid lightgray; margin: 0.5rem; padding: 0.25rem 0.4rem; }
.div.selected { border-color: lightgreen; }
<div class="div div__first"></div>
<div class="div div__second"></div>
<div class="div div__third"></div>
<p>I have selected:<span class="selectedCountry"></span></p>
Jax-p
  • 7,225
  • 4
  • 28
  • 58
0

const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');
const selectedCountry = document.getElementsByClassName('selectedCountry')[0];

function clearSelection() {
  divList.forEach(function(div) {
    div.classList.remove('active');
  })
}

divList.forEach(function(div, index){
    div.textContent = countries[index];
    div.addEventListener('click', function() {
      clearSelection();
      this.classList.add('active');
      selectedCountry.innerText = document.getElementsByClassName('active')[0].innerText;
    })
})
body{
    display: flex;
    height: 100vh;
    justify-content: center;
    align-items: center;
}

.div{
    margin-left: 10px;
    padding: 15px;
    border: 2px solid black;
    background-color: skyblue;
    cursor: pointer;
}

p{
    margin-left: 10px;
}

.active{
  background-color: yellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="div"></div>
    <div class="div"></div>
    <div class="div"></div>

    <p>I have selected:<span class="selectedCountry"></span></p>
    <script src="app.js"></script>
</body>
</html>
Tibike
  • 338
  • 2
  • 12
  • Hey man this code is really good, its intuitive, but iam little bit puzzled. why did u use `getElementsByClassname('selectedCountry)[0]` instead of using `querySelector('.selectedCountry')` I think the second solution is even more easy to undesrtand than your. does it have any advantages over my solution? Thanks mate – Michał Soja Oct 26 '19 at 14:24
  • @MichałSoja There are some differences ([read more](https://stackoverflow.com/questions/14377590/queryselector-and-queryselectorall-vs-getelementsbyclassname-and-getelementbyid)) but in this case it is not important what function you are using – Tibike Oct 26 '19 at 16:35