I would like to display the names of the selected checkboxes when I click Submit.
For example:
- If no checkbox is checked display should be "Please select a hobby".
- If painting is checked display "#painting"
- If painting and reading is checked display "#reading#painting"
The below given code is not working.
function displayHobbies(){
let HobbiesInput=[document.getElementById('dancing'),
document.getElementById('reading'),
document.getElementById('painting')];
var HobbiesError="";
for(var i=0;i<HobbiesInput.length;i++)
{
if (HobbiesInput[i].checked==false)
{
HobbiesError="Please select a hobby";
}
else
{
HobbiesError +="#"+HobbiesInput[i].name;
}
}
document.getElementById('hobbies_display').innerHTML=HobbiesError;
}
<form name= "myform" onclick="displayHobbies()">
Hobby <input type="checkbox" id="dancing" name="dancing">
<label for="dancing">Dancing</label>
<input type="checkbox" id="reading" name="reading">
<label for="reading">Reading</label>
<input type="checkbox" id="painting" name="painting">
<label for="painting">Painting</label>
<button type="button" id="hobby_submit">Submit</button>
</form>
Hobbies:<label id="hobbies_display"></label>
hobbies_displaylabel every time something is clicked. Second, your for loop doesn't check to see if they're all unchecked to display that message, it checks if any are unchecked. So if the first two are checked, but the last one isn't, it'll look at that last one, see that it's unchecked, and then set the message to say that nothing is checked.