jeudi 27 octobre 2022

Hiding the div and li elements when checkbox is checked/unchecked

Can anyone guide me in the correct direction please? I'm stuck with checked and not checked checkboxes. What needs to be added:

  • Text in the text field & checkbox checked - hides the div element
  • Text in the text field & checkbox unchecked by entry - hides the first li element
  • Empty text field by entry & checkbox checked hides the second li element

What I have now:

let txt = document.getElementById("name")
let but = document.getElementById("send")
let out = document.getElementById("greeting")
let divv = document.getElementById("errors")
let nameError = document.getElementById("name-error")
let consError = document.getElementById("consent-error")
let cons = document.getElementById("consent")

but.disabled = true
divv.style.display = "block" 

cons.addEventListener("input", function() {
if (cons.checked && txt.value !== ''){
  consError.style.display = "none"
  but.disabled = false
  } else {
    consError.style.display = "block"
    but.disabled = true
  }
})

txt.addEventListener("input", function(){
  if (txt.value !== '' && cons.checked === false ) {
  but.disabled
  } else {
    but.disabled = false
  }
})

function fun () {
  out.textContent =  "Hey " + txt.value + "!"
}

but.addEventListener("click",fun)

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>A checkbox</title>
  </head>
  <body>
    <label for="name">Name</label>
    <input id="name" placeholder="Name">
    <label>
      <input id="consent" type="checkbox">
      I agree
    </label>
    <input id="send" type="button" value="Submit">
    <p id="greeting"></p>
    <div id="errors" style="color: red; display: none;">
      <p>Error:</p>
      <ul>
        <li id="name-error">Please enter a name</li>
        <li id="consent-error">Please give consent</li>
      </ul>
    </div>
    <script src="index.js"></script>
  </body>
</html>

Before I had cons.addEventListener like this and it was hiding the second li element but didn't keep the button disabled

cons.addEventListener("input", function() {
if (cons.checked){
  consError.style.display = "none"
  } else {
    consError.style.display = "block"
  }
})



Aucun commentaire:

Enregistrer un commentaire