javascript - jQuery多选更改事件无法按选择顺序获取选项值
问题描述
我想在更改选择时将多个选项存储在隐藏的输入中(例如,我选择最后一个选项,然后选择第一个选项)我输入相同的顺序。
$('select').change(function() {
var str = "";
// For multiple choice
$("select option:selected").each(function() {
str = $(this).val() + str + " ";
});
alert(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands[]" multiple="multiple">
<option value="1">BASTIEN test0</option>
<option value="2">BASTIEN test1</option>
<option value="3">BASTIEN test2</option>
</select>
现在如果我改变例如
(BASTIEN 测试1/BASTIEN 测试2/BASTIEN 测试0)
当我运行我的代码时,我得到
(BASTIEN 测试0/BASTIEN 测试1/BASTIEN 测试2)
这是我的代码工作正常但是当我选择最后一个然后是第二个时这里的问题是当我选择第三个时它们不起作用并且我没有在我的 var 中获得我的选项的值
解决方案
如果我理解正确,这可能会有所帮助:
使用点击事件直接定位选项并将它们按顺序保存在数组中。与e.target.selected ?
您一起确保仅在选定时进行推送。
remove
如果取消选择,函数将从数组中删除元素。
var str = []
$('select#brands option').on("click", function(e) {
let l = $(e.target).parent().find("option:selected").length
console.clear()
if (l > 1) {
e.target.selected ? str.push(e.target.value) : remove(str, e.target.value);
} else if (l === 1 && str.length != 2) {
str = [e.target.value]
} else if (l === 1 && str.length === 2) {
remove(str, e.target.value)
} else if (l === 0) {
str = []
}
console.log(str)
});
function remove(str, item) {
var index = str.indexOf(item);
if (index !== -1) {
str.splice(index, 1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands" multiple="multiple">
<option value="1">BASTIEN test1</option>
<option value="2">BASTIEN test2</option>
<option value="3">BASTIEN test3</option>
<option value="4">BASTIEN test4</option>
</select>
推荐阅读
- c++ - QGLViewer 最小示例失败。正确的依赖设置未知
- r - 如何对两个表进行特定的复杂绑定
- python - 静音命令失败并显示“AttributeError:'NoneType' 对象没有属性 'id'”
- java - 在 java/spring rest 中监控 rest API 调用
- r - clang-7:错误:链接器命令失败,macOS Big Sur 的退出代码为 1
- python - python切片中的“a[:,1]”是什么意思
- c# - 如何在收集到一定数量的硬币后才能进入下一个级别?
- r - 计算 R 中不同操作的日期之间的差异
- c++ - 自动删除拷贝构造函数与赋值的关系
- javascript - Twig 将参数作为 JSON 传递给 JS