I'm creating an app that allows a teacher to create a report for a student. My current jsfiddle shows the full code, and it has the basic functionality I want. However, at the moment the printSelection function runs onChange when the user chooses from the options, adding the selection to collatedArray.
function printSelection(e) {
collatedArray.push(e.value);
console.log(collatedArray);
}
The problem is, if the user changes their mind it then adds both of the options to final report.
Is there a way to run this function but only if the user has not made a selection from it before?
The problem in your case is that you are pushing data on each onchange
event, and doing so will only work if the user selects only once, but you can avoid that by using a simple object to hold your data and each time the user selects it overwrites the correct property that way you will store only the desired input, here is a simple example, note that you can use event delegation like me, instead of adding an event listener to each <select>
element, and pls avoid using inline JS it has lot of disadvantages.
var inputsElement = document.querySelector("#dropdown-inputs"),
inputs = {};
inputsElement.onchange = function(e) {
// note that I'm not checking for the type of element
// because I have just two <select> elements so it's
// obvious that one of them is triggering the "onchange" event
// so I set the right property name according to the select element
inputs[e.target.name] = e.target.value;
// just for debugging ;)
console.clear();
console.log(inputs);
}
<div id="dropdown-inputs">
Width:
<select name="width">
<option value="0">0</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
Height:
<select name="height">
<option value="0">0</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</div>