Skip to content

is it possible to combine these two functions into one?

I have two functions that are basically identical. The first function gets passed a mouse event where event.target is the input type=’checkbox’ the second function gets passed the input type=’checkbox’ is there a way to rewrite these into one function?

function crewChecked(event){                
    if(event.target.checked){
        names.push(event.target.value)
    }else{
        for(let i = 0; i < names.length;i++){
            if(names[i] == event.target.value){
                names = names.filter((name, index) => index !== i);
                break;
            }
        }
    }
    if(names.length==0){
        document.getElementById('dropdownCrewButton').innerText = "Select Crew"
    }else{
        document.getElementById('dropdownCrewButton').innerText = names.length + " crew"
    }
}


function crewChecked2(crewCheckbox){
    if(crewCheckbox.checked){
        names.push(crewCheckbox.value)
    }else{
        for(let i = 0; i < names.length;i++){
            if(names[i] == crewCheckbox.value){
                names = names.filter((name, index) => index !== i);
                break;
            }
        }
    }
    if(names.length==0){
        document.getElementById('dropdownCrewButton').innerText = "Select Crew"
    }else{
        document.getElementById('dropdownCrewButton').innerText = names.length + " crew"
    }
}

Answer

The only part of these two functions that differ are how you get the reference to the checkbox. So if you figure out how to get that checkbox in both cases, you’re golden.

Something like:

function crewChecked(eventOrCheckbox){          
      
    // Added
    const checkbox = eventOrCheckbox.target || eventOrCheckbox

    if(checkbox.checked){
        names.push(checkbox.value)
    }else{
        for(let i = 0; i < names.length;i++){
            if(names[i] == checkbox.value){
                names = names.filter((name, index) => index !== i);
                break;
            }
        }
    }
    if(names.length==0){
        document.getElementById('dropdownCrewButton').innerText = "Select Crew"
    }else{
        document.getElementById('dropdownCrewButton').innerText = names.length + " crew"
    }
}

This line checks for a target property on the eventOrCheckbox argument. If there is one, then it’s an event and the checkbox should be saved to checkbox. If there isn’t, then assume this argument is the checkbox and continue on.