简体   繁体   中英

Why is my JavaScript/JQuery adding and removing class with function not working?

Hi guys I ran into major problems today.

When the user types in texts on the fields and then presses submit, the user input text should appear on the caption below the image, which was previously .invisible but I remove it using jquery when user presses submit. I also use .html to change the html to the user's text input. I have marked out this part (see comment: // Displaying captions that user chose in javascript).

However that isn't happening...can someone please help thanks....

Here is my javascript:

    function diceRoll() {
  // 1st dice
  var randomNumber1 = Math.floor(Math.random() * 6 + 1);
  var Image1 = "dice" + randomNumber1 + ".png";
  document.querySelectorAll("img")[1].setAttribute("src", Image1);

  // 2nd dice
  var randomNumber2 = Math.floor(Math.random() * 6 + 1);
  var Image2 = "dice" + randomNumber2 + ".png";
  document.querySelectorAll("img")[2].setAttribute("src", Image2);

  // 3rd dice
  var randomNumber3 = Math.floor(Math.random() * 6 + 1);
  var Image3 = "dice" + randomNumber3 + ".png";
  document.querySelectorAll("img")[3].setAttribute("src", Image3);

  // 4th dice
  var randomNumber3 = Math.floor(Math.random() * 6 + 1);
  var Image4 = "dice" + randomNumber3 + ".png";
  document.querySelectorAll("img")[4].setAttribute("src", Image4);
}


// Responding to Dropdown Button
let links = document.querySelectorAll('#list li')
links.forEach((el) => {
  el.addEventListener('click', (event) => {
    let numberOfChoices = event.target.innerText
    document.getElementById('dropdownMenu').innerHTML = `${numberOfChoices}<span class="caret"></span>`

    if (numberOfChoices === "2") {
      $("#img3, #img4, .threeChoices, .fourChoices").addClass("invisible")
    }
    if (numberOfChoices === "3") {
      $("#img4, .fourChoices").addClass("invisible");
      $("#img3, .threeChoices").removeClass("invisible")
    }
    if (numberOfChoices === "4") {
      $("#img3, #img4, .threeChoices, .fourChoices").removeClass("invisible");
    }
  })
})

// Responding to Submit
document.getElementById("submit").addEventListener("click", function(e) {
  e.preventDefault();

// Storing Data into variables
  var choice1 = $("#choice1").val();
  var choice2 = $("#choice2").val();
  var choice3 = $("#choice3").val();
  var choice4 = $("#choice4").val();
  var noOfChoices = $("#dropdownMenu").text();

// Rotate animation
  $(".dice").addClass("rotate");

// Changing text to user input
      $("#caption1").html(choice1);
      $("#caption2").html(choice2);
      $("#caption3").html(choice3);
      $("#caption4").html(choice4);

// Displaying captions that user chose
    if (noOfChoices === "2") {
      $("#caption1, #caption2").removeClass("invisible");
      $("#caption3, #caption4").addClass("invisible");
    }

    if (noOfChoices === "3") {
      $("#caption1, #caption2, #caption3").removeClass("invisible");
      $("#caption4").addClass("invisible");
    }

    if (noOfChoices === "4") {
      $(".caption").removeClass("invisible");
    }

// Rolling Dice
  diceRoll();

// Determining winner


})


var diceNumbers = []

And here is my html:

   <!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Diceey</title>

  <!-- Bootstrap, CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">

  <!-- Jquery Links -->
  <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.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>

<body>
    
      <!-- Images -->
  <div class="container-fluid">

    <div class="container-of-images">
      <img src="chick2.png">

      <figure>
        <img id="img1" class="dice" src="dice6.png">
        <figcaption class="caption" id="caption1">Choice 1</figcaption>
      </figure>

      <figure>
        <img id="img2" class="dice" src="dice6.png">
        <figcaption class="caption" id="caption2">Choice 2</figcaption>
      </figure>

      <figure class="threeChoices">
        <img id="img3" class="dice" src="dice6.png">
        <figcaption class="caption" id="caption3">Choice 3</figcaption>
      </figure>

      <figure class="fourChoices">
        <img id="img4" class="dice" src="dice6.png">
        <figcaption class="caption" id="caption4">Choice 4</figcaption>
      </figure>
      <img src="chick1.png">
    </div>
  </div>


<!-- Forms -->

<div class="container-fluid">

    <h5>Write down your choices here (up to 4):</h5>
  <div class="container-of-forms">

    <!-- Dropdown Button -->
    <div class="dropdown">
      <button class="btn btn-info dropdown-toggle" type="button" id="dropdownMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
        2
        <span class="caret"></span>
      </button>
      <ul id="list" class="dropdown-menu dropdown-info" aria-labelledby="dropdownMenu">
        <li><a href="#">2</a></li>
        <li><a href="#">3</a></li>
        <li><a href="#">4</a></li>
      </ul>

      <!-- Input Text Fields -->
      <div class="container-inner">
        <input class="text-input-box" id="choice1" type="text" name="" value="" placeholder="Choice 1"> <br>
        <input class="text-input-box" id="choice2" type="text" name="" value="" placeholder="Choice 2"> <br>
        <input class="text-input-box invisible threeChoices" id="choice3" type="text" name="" value="" placeholder="Choice 3"> <br>
        <input class="text-input-box invisible fourChoices" id="choice4" type="text" name="" value="" placeholder="Choice 4">
      </div>
    </div>



  </div>
  <!-- Submit Button -->
  <a href="" id="submit" class="btn btn-info btn-lg" role="button">Go</a>
</div>

  <script src="index.js" charset="utf-8">
  </script>
</body>
</html>

And here is my css:

img {
  width: 80px;
  line-height: 0;
  margin: 0 1%;
  display: inline-block;
  justify-content: center;
  vertical-align: middle;
}

figcaption {
  text-align:
    center;
  width: 100px;
  font-size: 1.5rem;
  color: #5b8c85;
  font-family: 'Indie Flower', cursive;
}

figure {
  display: inline-block;
  vertical-align: middle;
}

.rotate {
  animation: rotation 0.3s infinite linear;
  animation-iteration-count: 2;
}

@keyframes rotation {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(359deg);
  }
}

.invisible {
  display: none;
}

.hidden {
  visibility: hidden;
}

Start by changing this

var noOfChoices = $("#dropdownMenu").text();

To

var noOfChoices = $("#dropdownMenu option:selected").text();

To get the text form the drop down box.Try

I ran your code and it seems that changing var noOfChoices = $("#dropdownMenu").text() to var noOfChoices = $("#dropdownMenu").text().trim() will do the trick.

Somehow getting the drop-down menu text() will have whitespace at the beginning, that is why all your if statements always return false.

This should be the js code with a few other modifications that you will find commented.

// Responding to Dropdown Button
let links = document.querySelectorAll("#list li");
links.forEach((el) => {
  el.addEventListener("click", (event) => {
    let val = event.target.innerText;
    document.getElementById(
      "dropdownMenu"
    ).innerHTML = `${val}<span class="caret"></span>`;

    if (val === "2") { /* numberOfChoices changed to val */
      $("#img3, #img4, .threeChoices, .fourChoices").addClass("invisible");
    }
    if (val === "3") { /* numberOfChoices changed to val */
      $("#img4, .fourChoices").addClass("invisible");
      $("#img3, .threeChoices").removeClass("invisible");
    }
    if (val === "4") { /* numberOfChoices changed to val */
      $("#img3, #img4, .threeChoices, .fourChoices").removeClass("invisible");
    }
  });
});

// Responding to Submit
document.getElementById("submit").addEventListener("click", function (e) {
  e.preventDefault();

  // Storing Data into variables
  var choice1 = $("#choice1").val();
  var choice2 = $("#choice2").val();
  var choice3 = $("#choice3").val();
  var choice4 = $("#choice4").val();
  var noOfChoices = $("#dropdownMenu").text().trim(); /* adding .trim() here */

  // Rotate animation
  $(".dice").addClass("rotate");
  setTimeout(() => {
    $(".dice").removeClass("rotate");
  }, 1000);

  // Changing text to user input
  $("#caption1").html(choice1);
  $("#caption2").html(choice2);
  $("#caption3").html(choice3);
  $("#caption4").html(choice4);

  // Displaying no. of Captions that User Chose
  if (noOfChoices === "2") {
    $("#caption1, #caption2").removeClass("invisible");
    $("#caption3, #caption4").addClass("invisible");
  }

  if (noOfChoices === "3") {
    $("#caption1, #caption2, #caption3").removeClass("invisible");
    $("#caption4").addClass("invisible");
  }

  if (noOfChoices === "4") {
    $(".caption").removeClass("invisible");
  }

  // Rolling Dice
  diceRoll();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM