简体   繁体   中英

Checking if HTML Checkbox is Checked

I made a simple HTML website using HTML and JavaScript that suggests a song based on the attributes that the user selects. I have everything working, However, for example, in the image below, the second "else-if" statement and the last "else-if" statement end up returning the song title of the second "else-if" statement. In the last statement, it will return the song title that is in the second "else-if" statement. It looks like it is ignoring the band[0].checked part of the condition of the last "else-if" statement. I am unsure why it is just ignoring that part of the condition for the statement? My code for this part is below:

Everything works as it should, except for the last two "else-if" statements because of the issue I stated above.

var genre = document.getElementById("songGenre").value;
var bandList = document.getElementsByName("bandList");
var band = document.getElementsByName("band");

if (genre == "Rock" && bandList[0].checked && band[1].checked && band[2].checked) {
  alert("Our song suggestion: Tip the Scales");
}

else if (genre == "Rock" && bandList[0].checked && band[1].checked && band[3].checked) {
  alert("Our song suggestion: Savior");
}

else if (genre == "Rock" && bandList[0].checked && band[0].checked && band[2].checked) {
  alert("Our song suggestion: Hero of War");
}

else if (genre == "Rock" && bandList[0].checked && band[0].checked && band[3].checked) {
  alert("Our song suggestion: Swing Life Away");
}

else if (genre == "Rock" && bandList[0].checked && band[0].checked && band[1].checked && band[2].checked) {
  alert("Our song suggestion: Entertainment");
}

else if (genre == "Rock" && bandList[0].checked && band[0].checked && band[1].checked && band[3].checked) {
  alert("Our song suggestion: Elective Amnesia");
}

This is happening because when the condition:

(genre == "Rock" && bandList[0].checked && band[0].checked && band[1].checked && band[3].checked)

is true, then

(genre == "Rock" && bandList[0].checked && band[1].checked && band[3].checked)

is also true.

However, since you are using elseif, it will stop at the second condition and not continue checking down the line.

In order to fix this, you need to change the order of you elseif blocks, and put the most specific one in the top, and the more generic one in the bottom. In other words, put the longer complex if's on top, and simple short ones in the bottom.

Once you fix the order from specific --> simple, you will see your application behaving as expected.

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