Combining two event listeners for one result

Hi,
I’m trying to combine the output from two Event Listeners into one result. See my HTML code below. I have two dropdown lists and I want the value in the paragraph below (id=“units”) to show the combination of whatever is selected in both dropdown lists e.g. Value of Dropdown list 1 + “/” + Value of Dropdown list 2.

I can do this using the Event Listener ‘input’ with one Dropdown list but struggling with combining the output from two. See my attempted JavaScript code below the HTML.

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <p>from:</p>
        <label for="mass">mass</label>
        <select id="mass" name="units">
            <option value="Kg">Kg</option>
            <option value="g">g</option>
            <option value="mg">mg</option>
        </select>
        <label for="volume">volume</label>
        <select id="volume" name="units">
            <option value="L">L</option>
            <option value="mL">mL</option>
            <option value="uL">uL</option>
        </select>
        <br>
        <br>
        <p>to:</p>
        <strong><p id="units">Show units here</p></strong>
        <script src="main.js"></script>
    </body>
</html>
const mass = document.getElementById("mass");
const volume = document.getElementById("volume");
const units = document.getElementById("units")

mass.addEventListener('input', showMass);
volume.addEventListener('input', showVol);


const newMass = function showMass(event) {
    return event.target.value 
}

const showVol = function showVol(event) {
    return event.target.value
};

units.textContent = newMass + '/' + showVol;

Thanks,

Alex

One strategy you could use is to add events to both elements but use the same handler function. You can still retrieve the same information using the selectors for each of them without having to use the event object. You’d also be able to use this handler to call any other functions you add in future to update the calculations if/when you add input fields for the numbers.

Click here if you need an example of how this could work
const unitChange = () => {
  units.textContent = mass.value + '/' + volume.value;
};

mass.addEventListener('input', unitChange);
volume.addEventListener('input', unitChange);

// Call it directly once to set the initial value of your #units p
unitChange();

Thanks. That worked :slightly_smiling_face:
I thought handler function would always need a parameter

1 Like