Issue
I'm looking to select an array based on a selected option. I need to store another value in the array, based on the selected option. I'm struggling to find a resource online for the best way to approach this, and the only way I can think of in my head is using if, but the number of potential options is quite large (60 options), so that will become very messy, very quickly. The user will be able to add multiple options to each array.
I've considered creating an array of arrays and using a number value to select the correct array within the master array, but I would prefer to be able to select by name if that would be possible.
For the example below, the count of the colours stored in the array and selected colours will be passed to a Google Sheet in GAS and must appear like this (I'm happy with this, I can do this fine):
Car Choice | Count | Colours |
---|---|---|
BMW | 3 | Blue, Blue, Red |
VW | 2 | Green, Yellow |
HTML
<select id="car">
<option value="BMW">BMW</option>
<option value="VW">VW</option>
</select>
<input id="colour"></input>
JS
function storeCar() {
let BMW = [];
let VW = [];
let carChoice = document.getElementById("car").value;
let colourChoice = document.getElementById("colour").value;
// some script here to select the correct object to store the car in based on the choice
BMW.push(colourChoice);
}
With a result something like...
BMW = ["Blue","Blue","Red"];
Solution
I've considered creating an array of arrays and using a number value to select the correct array within the master array, but I would prefer to be able to select by name if that would be possible.
This is certainly possible, you would just need to amend the format you store your data in to be an object instead of an array. That way you can use array notation to access the object via the key, which would match the value selected in the dropdown.
const carSelect = document.querySelector('#car');
const colourInput = document.querySelector('#colour');
const sourceData = {
"BMW": ["Blue", "Blue", "Red"],
"VW": ["Green", "Yellow"]
}
carSelect.addEventListener('change', e => {
colourInput.value = sourceData[e.target.value] || '';
});
<select id="car">
<option value="">Please select...</option>
<option value="BMW">BMW</option>
<option value="VW">VW</option>
</select>
<input id="colour"></input>
Answered By - Rory McCrossan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.