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. Please suggest changes to correct it.
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>
Aucun commentaire:
Enregistrer un commentaire