I wonder if there is a way to get a certain element of an array, which is stored in a single value. Sounds weird, I know, but this is my problem:
HTML
<select id="select">
<option value='{"array":["a","b"]}'>Option</option>
</select>
<button onClick="getArrayIndex()">Button</button>
--> I got one array with two elements (a and b) stored isnide one value in an option tag.
JS
function getArrayIndex() {
alert(option.value[0]);
}
So what I need is that the alert message displays only one element of the array, I hope this is somehow possible, thanks for answers! As you can see I tried to display only element 0, in this case "a", but it doesn't work. I also tried these:
alert(option.value.array[0]);
alert(option.value.array(0));
alert(option.value(0));
alert(option.value.[0]);
...and so on. But none of these work.
Your value is a string containing JSON defining an object containing an array property with an array, rather than actually being an array. To use just the first element in that array, you need to parse the JSON into the object and array, then access the array from the object and get its first element:
alert(JSON.parse(option.value).array[0]); // "a"
Note that your getArrayIndex function currently uses an option identifier that doesn't appear to be defined anywhere. If you want to use the currently-selected value in the select, then:
function getArrayIndex() {
const select = document.getElementById("select");
const value = select.value;
if (value) {
alert(JSON.parse(value).array[0]);
}
}
Side note: I would xyz-attribute-style event handlers. Instead, hook up the event handler using modern techniques (such as addEventListener). Also beware that the default type of the button element is "submit", so if that button is in a form, by default it will submit the form.