简体   繁体   English

如何动态获取输入的值

[英]How to get the value of an input dynamically

Currently I am storing the values of the text inputs and selects from a table in the options variable.目前我正在存储文本输入的值并从options变量中的表中进行选择。

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;我想用类似的东西来获得它: options[5].val; But obviously it doesn't work.但显然它不起作用。

What is the most typical/correct JavaScript way of achieving a similar result?实现类似结果的最典型/正确的 JavaScript 方法是什么?

this way: with the help of selectedOptions这样:在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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM