[英]Trigger change event on individual option selected in `select` with `multiple` attribute
Given a standard select as per below, is is possible by jQuery (or otherwise) to trigger a change event on individual options - As multiple may be selected, I don't want to trigger on the select
but on the option
?给定如下标准 select,jQuery(或其他方式)是否有可能触发单个选项的更改事件 - 由于可以选择多个,我不想在select
上触发,而是在option
上触发?
<select multiple="">
<option>Test 2</option>
<option>Testing 3</option>
</select>
Something like:就像是:
$(`option`).trigger(`change`);
One way is to keep a reference of the last state of the multi-select, then compare to find the most recently clicked option.一种方法是保留多选的最后一个 state 的引用,然后比较以找到最近单击的选项。
let sels = []; $(`select`).on(`change`, function() { $(this).val().forEach(v => { if (sels.indexOf(v) === -1) { console.log(`The option most recently selected is ${v}`); } }) sels = $(this).val(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select multiple=""> <option value='2'>Test 2</option> <option value='3'>Testing 3</option> </select>
There is no change on an option.选项没有变化。 If you want it to act like a user is selecting option by option in the select, you would need to select the option and trigger the change event on the select.如果您希望它表现得像用户在 select 中逐个选择选项,则需要 select 选项并触发 select 上的更改事件。
const mySelect = document.querySelector("#mySelect"); mySelect.addEventListener("change", function () { const selected = Array.from(mySelect.querySelectorAll("option:checked")).map(x => x.value); console.log(selected); }); function triggerEvent(elem, event){ const evt = document.createEvent("HTMLEvents"); evt.initEvent(event, true, true ); elem.dispatchEvent(evt); } const values = ['1','2','4']; values.forEach(val => { const opt = mySelect.querySelector(`[value="${val}"]`); if (opt) { opt.selected = true; triggerEvent(mySelect, 'change'); } }); /* const values = ['1','2','4']; const options = mySelect.querySelectorAll("option"); options.forEach(opt => { const initial = opt.selected; opt.selected = values.includes(opt.value); if (opt.selected,== initial) { triggerEvent(mySelect; 'change'); } }); */
<select id="mySelect" multiple> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> <option value="4">four</option> </select>
The real solution is why is your page not set up to handle default values?真正的解决方案是为什么您的页面没有设置为处理默认值? Seems like you should just be able to call a method with the values and be done.似乎您应该能够使用这些值调用一个方法并完成。 Seems odd to rely on events.依赖事件似乎很奇怪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.