Removing a class from a div by clicking on the select option

Asked

Viewed 44 times

-1

Come on, I want to do the following, when I select an option from select it load the text of the selected option and show in a textarea, until then it’s ok, it’s working, but I also wanted when clicking on an option it load a div according to the selected option. for example I click on the first option it loads the div.one, when you click on the two option it loads the div-two and hide the div.one and so on. Since all Divs should start hidden so it is with the Hide class. Note: I want to do it in pure javasript without jquery.

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>teste</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="css/estilo.css">
    </head>
    <body>
        <div class="container">
            <form>
                <div class="form-group">
                  <label for="exampleFormControlSelect1">Example select</label>
                    <select class="form-control" id="exampleFormControlSelect1">
                        <option  onclick="eventoClickNull()" value="">Selecione</option>
                        <option  onclick="eventoClick()" value="1">item1</option>
                        <option  onclick="eventoClick()" value="2">item2</option>
                        <option  onclick="eventoClick()" value="3">item3</option>
                    </select>
                </div>
                <div class="form-group">
                  <label for="exampleFormControlTextarea1">Example textarea</label>
                  <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
                </div>
              </form>
              <div class="row">
                  <div class="col">
                    <div divs class="one hide">
                      <p><b>DIV 1</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam maximus non magna id lacinia. Fusce blandit laoreet mi ut accumsan. Nullam at erat eget lectus condimentum iaculis eu vitae sem. Nunc lobortis tincidunt lobortis. Morbi leo diam, facilisis et convallis nec, aliquet et neque. Vivamus venenatis tincidunt nunc sit amet feugiat. Aenean tristique odio vitae sem tristique, sit amet euismod orci vehicula. In varius blandit est. Nunc sed augue fringilla, finibus nisi a, suscipit quam. Nullam feugiat velit eget mi vestibulum, at varius massa tincidunt. Praesent auctor, est sit amet interdum finibus, magna risus fringilla lectus, eu tincidunt tortor ipsum nec augue. Cras ut lectus tempor, ultricies mi non, ultricies risus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed ut mauris arcu. Aliquam a mi mauris.</p>
                    </div>
                    <div divs class="two hide">
                        <p><b>DIV 2</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam maximus non magna id lacinia. Fusce blandit laoreet mi ut accumsan. Nullam at erat eget lectus condimentum iaculis eu vitae sem. Nunc lobortis tincidunt lobortis. Morbi leo diam, facilisis et convallis nec, aliquet et neque. Vivamus venenatis tincidunt nunc sit amet feugiat. Aenean tristique odio vitae sem tristique, sit amet euismod orci vehicula. In varius blandit est. Nunc sed augue fringilla, finibus nisi a, suscipit quam. Nullam feugiat velit eget mi vestibulum, at varius massa tincidunt. Praesent auctor, est sit amet interdum finibus, magna risus fringilla lectus, eu tincidunt tortor ipsum nec augue. Cras ut lectus tempor, ultricies mi non, ultricies risus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed ut mauris arcu. Aliquam a mi mauris.</p>
                    </div>
                    <div divs class="three hide">
                        <p><b>DIV 3</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam maximus non magna id lacinia. Fusce blandit laoreet mi ut accumsan. Nullam at erat eget lectus condimentum iaculis eu vitae sem. Nunc lobortis tincidunt lobortis. Morbi leo diam, facilisis et convallis nec, aliquet et neque. Vivamus venenatis tincidunt nunc sit amet feugiat. Aenean tristique odio vitae sem tristique, sit amet euismod orci vehicula. In varius blandit est. Nunc sed augue fringilla, finibus nisi a, suscipit quam. Nullam feugiat velit eget mi vestibulum, at varius massa tincidunt. Praesent auctor, est sit amet interdum finibus, magna risus fringilla lectus, eu tincidunt tortor ipsum nec augue. Cras ut lectus tempor, ultricies mi non, ultricies risus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed ut mauris arcu. Aliquam a mi mauris.</p>
                    </div>
                  </div>
              </div>
        </div>        
    </body>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
    <script src="js/script2.js"></script>
</html>

JS

function eventoClick(){
    let e = document.getElementById("exampleFormControlSelect1");
    let itemSelecionado = e.options[e.selectedIndex].text;
    let textArea = document.getElementById("exampleFormControlTextarea1");
    textArea.innerHTML = itemSelecionado

    let divs = document.querySelector('[divs]')    
    divs.classList.remove("hide")
}

function eventoClickNull(){
    let e = document.getElementById("exampleFormControlSelect1");
    let itemSelecionado = e.options[e.selectedIndex = "0"].text;
    let textArea = document.getElementById("exampleFormControlTextarea1");
    textArea.innerHTML = " "
}

1 answer

1

Some things wrong:

  • let divs = document.querySelector('[divs]') returns the first element, you must use querySelectorAll and iterate with a foreach
  • The onclick in the element option does not do what you seek, you must use the onchange in the select
  • e.selectedIndex = "0" is an assignment, not a comparison as you intend...

My suggestion:

const select = document.getElementById('exampleFormControlSelect1');
const textarea = document.getElementById('exampleFormControlTextarea1');
const divs = document.querySelectorAll('[divs]');


function eventoClick() {
  const selectedIndex = select.selectedIndex - 1;
  divs.forEach((el, i) => el.classList.toggle("hide", i !== selectedIndex));
  textarea.innerHTML = getSelectText(select);
}

function getSelectText(selectElement) {
  // a ideia de usar -1 aqui é só para o caso de ser `0`o código não ir buscar o texto do 
  // option e considerar como "não selecionável". Uma alternativa seria mascá-lo como "disabled"
  const selectedIndex = selectElement.selectedIndex || -1;
  const selectedOption = selectElement.options[selectedIndex];
  return selectedOption ? selectedOption.text : '';
}
[divs].hide {
  display: none;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" href="css/estilo.css">

<div class="container">
  <form>
    <div class="form-group">
      <label for="exampleFormControlSelect1">Example select</label>
      <select class="form-control" id="exampleFormControlSelect1" onchange="eventoClick()">
        <option value="">Selecione</option>
        <option value="1">item1</option>
        <option value="2">item2</option>
        <option value="3">item3</option>
      </select>
    </div>
    <div class="form-group">
      <label for="exampleFormControlTextarea1">Example textarea</label>
      <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
    </div>
  </form>
  <div class="row">
    <div class="col">
      <div divs class="one hide">
        <p><b>DIV 1</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam maximus non magna id lacinia. Fusce blandit laoreet mi ut accumsan. Nullam at erat eget lectus condimentum iaculis eu vitae sem. Nunc lobortis tincidunt lobortis. Morbi
          leo diam, facilisis et convallis nec, aliquet et neque. Vivamus venenatis tincidunt nunc sit amet feugiat. Aenean tristique odio vitae sem tristique, sit amet euismod orci vehicula. In varius blandit est. Nunc sed augue fringilla, finibus nisi
          a, suscipit quam. Nullam feugiat velit eget mi vestibulum, at varius massa tincidunt. Praesent auctor, est sit amet interdum finibus, magna risus fringilla lectus, eu tincidunt tortor ipsum nec augue. Cras ut lectus tempor, ultricies mi non,
          ultricies risus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed ut mauris arcu. Aliquam a mi mauris.</p>
      </div>
      <div divs class="two hide">
        <p><b>DIV 2</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam maximus non magna id lacinia. Fusce blandit laoreet mi ut accumsan. Nullam at erat eget lectus condimentum iaculis eu vitae sem. Nunc lobortis tincidunt lobortis. Morbi
          leo diam, facilisis et convallis nec, aliquet et neque. Vivamus venenatis tincidunt nunc sit amet feugiat. Aenean tristique odio vitae sem tristique, sit amet euismod orci vehicula. In varius blandit est. Nunc sed augue fringilla, finibus nisi
          a, suscipit quam. Nullam feugiat velit eget mi vestibulum, at varius massa tincidunt. Praesent auctor, est sit amet interdum finibus, magna risus fringilla lectus, eu tincidunt tortor ipsum nec augue. Cras ut lectus tempor, ultricies mi non,
          ultricies risus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed ut mauris arcu. Aliquam a mi mauris.</p>
      </div>
      <div divs class="three hide">
        <p><b>DIV 3</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam maximus non magna id lacinia. Fusce blandit laoreet mi ut accumsan. Nullam at erat eget lectus condimentum iaculis eu vitae sem. Nunc lobortis tincidunt lobortis. Morbi
          leo diam, facilisis et convallis nec, aliquet et neque. Vivamus venenatis tincidunt nunc sit amet feugiat. Aenean tristique odio vitae sem tristique, sit amet euismod orci vehicula. In varius blandit est. Nunc sed augue fringilla, finibus nisi
          a, suscipit quam. Nullam feugiat velit eget mi vestibulum, at varius massa tincidunt. Praesent auctor, est sit amet interdum finibus, magna risus fringilla lectus, eu tincidunt tortor ipsum nec augue. Cras ut lectus tempor, ultricies mi non,
          ultricies risus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed ut mauris arcu. Aliquam a mi mauris.</p>
      </div>
    </div>
  </div>
</div>

  • Ball show, thanks for the explanation, but I’m still looking for something more concrete, so using toggle gets a little weird because I click on one there then click on another toggle gets a little lost and the Divs are appearing together, in case two, wanted something using this maybe, but thank you very much.

  • @Fernandopinhel had placed === instead of !==, i.e., the logic was reversed, hid the selected and showed the others. I corrected.

  • Yes!! Beauty my friend, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.