Reputation: 2082
Currently I am storing the values of the text inputs and selects from a table in the options
variable.
var options = $(tbody).find("select option:selected").map( (_, e) => $(e).text().trim() ).get();
var msgs = $(tbody).find("input[type='text']").map( (_, e) => $(e).val().trim() ).get();
options.splice(2, 0, msgs[0]);
options.splice(4, 0, msgs[1]);
The thing is, for selects, in addition to the text, I would also like to know the value.
I'd like to get it with something like: options[5].val;
But obviously it doesn't work.
What is the most typical/correct JavaScript way of achieving a similar result?
Upvotes: 0
Views: 56
Reputation: 22274
this way : with the help of selectedOptions
const mySelect = document.querySelector('select[name="my-select"]')
mySelect.onchange = () =>
{
console.clear()
Array.from(mySelect.selectedOptions)
.forEach(opt => { console.log(opt.value, opt.textContent ) })
}
select {
margin : 1em;
width : 7em;
text-align: center;
}
/***/
.as-console-wrapper { max-height:100% !important; top:0; left:70% !important; width:30%; }
.as-console-row { background-color: yellow; }
.as-console-row::after { display:none !important; }
<select name="my-select" size="8" multiple >
<option value="a"> aaaaa </option>
<option value="b"> bbbbb </option>
<option value="c"> ccccc </option>
<option value="d"> ddddd </option>
<option value="e"> eeeee </option>
<option value="f"> fffff </option>
<option value="g"> ggggg </option>
</select>
Upvotes: 1