简体   繁体   English

Javascript - 从多个 select 框中获取文本而不是值

[英]Javascript - get text instead of values from multiple select boxes

I´ve a form where user can add as much dropdowns as he needs.我有一个表单,用户可以根据需要添加尽可能多的下拉列表。 I need to save the text from the selected options from the dropdowns to the session.我需要将下拉列表中选定选项的文本保存到 session。

HTML: HTML:

<select name="codes[]" class="form-control-edited coinsurers-sv d-inline-block" placeholder="Please select">
    <option value="">Please select</option>
    <option value="1">Test 1</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

Javascript: Javascript:

<script>
let coInsuredPersonsSV = $('.coinsurers-sv').map(function (){ return $('.coinsurers-sv').find("option:selected").text() }).toArray();
sessionStorage.removeItem('co-insured-persons-hi-sv');

if (coInsuredPersonsSV.length > 0) {
sessionStorage.setItem('co-insured-persons-hi-sv', JSON.stringify(coInsuredPersonsSV));
}
</script>

Now lets say a user needs 3 dropdown forms and selects on every dropdown field another option.现在假设用户需要 3 个下拉菜单 forms 并在每个下拉字段上选择另一个选项。

Dropdown 1: Test 1
Dropdown 2: Test 2
Dropdown 3: Test 3

the result at my session storage is:我的 session 存储的结果是:

["Test 1   Test 2   Test 3", "Test 1   Test 2   Test 3", "Test 1   Test 2   Test 3"]

But the result should be:但结果应该是:

["Test 1", "Test 2", "Test 3"]

Can someone help me on how I need to change the.find function so that I get my desired results?有人可以帮助我了解我需要如何更改.find function 以便获得我想要的结果吗?

In the map callback function you select all dropdown lists, instead of the iterated one.map回调 function 你 select所有下拉列表,而不是迭代的一个。 So replace this code:所以替换这段代码:

return $('.coinsurers-sv').find

...with: ...和:

return $(this).find

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

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