Home > Software design >  Javascript returning multiple checkbox values
Javascript returning multiple checkbox values

Time:05-01

I'm having some trouble trying to get multiple checkbox values. It currently is working, just not in the way I wanted/was hoping it would. Right now anything checked is appended to the bottom of the body and not inline with the function it was aiming to be inserted into.

I'm trying to avoid using JQuery or anything except JavaScript as it's all we've currently covered in our class.

function favMedia(media){
    var media = document.forms['mediapref']['media'].value;
    return media;
}
function pets(pet){
    var pet = document.getElementsByName('pets')
    for (var checkbox of pet){
        if (checkbox.checked)
        document.body.append(checkbox.value   ' ');
    }
}
function about(text){
    var info = document.forms['personal']['about'].value;
    return info;
}

function infoForm(media, pet, text){
    document.getElementById('infoset').innerHTML = favMedia(media)   "<br>"   pets(pet)   "<br>"   about(text);
}

Is there some way I can assign it just to a single variable to return and then throw into the last function?

Also please give me any tips or improvements on any aspect of the functions if you have any.

CodePudding user response:

Put it in a string that you return from the function.

function pets(pet) {
  var pet = document.querySelector('[name="pets":checked');
  let selected = [...pet].map(p => p.value);
  return selected.join(', ');
}
  • Related