选择2 "change"事件不触发 htmx



这是我想要的方式:如果<select>被更改,那么htmx就会被触发。

<script src="https://unpkg.com/htmx.org@1.1.0"></script>
<table>
<tr hx-post="//example.com" hx-trigger="change">
<td>
<select name="runner">
<option value="a">a</option>
<option value="b">b</option>
</select>
</td>
</tr>
</table>

如果我使用django自动完成灯小部件,那么它不起作用。

我使用这个版本:django autocomplete light==3.8.1

刚刚遇到同样的问题,并用下面的guettli答案的修改版本修复了它。

window.addEventListener("DOMContentLoaded", (e) => {
$('select').on('select2:select', function (e) {
$(this).closest('select').get(0).dispatchEvent(new Event('change'));
});
});

如果我添加这个JS,那么它就可以工作了。我们欢迎更好的解决方案。

<script>
window.addEventListener("DOMContentLoaded", (e) => {
$('select').on('select2:select', function (e) {
$(this).closest('tr').get(0).dispatchEvent(new Event('change'));
});
})
</script>

对我来说,当使用bootstrap 5样式的Select2添加htmx.onLoad()时,它也起了作用https://apalfrey.github.io/select2-bootstrap-5-theme/:

htmx.onLoad(() => {
$("#collection-select").select2({
theme: "bootstrap-5",
closeOnSelect: true
});
});
window.addEventListener("DOMContentLoaded", (e) => {
$('select').on('select2:select', function (e) {
$(this).closest('select').get(0).dispatchEvent(new Event('change'));
});
});

对我有效的是使用htmx javascript APItrigger触发更改事件https://htmx.org/api/#trigger

window.addEventListener("DOMContentLoaded", (e) => {
$('select').on('select2:select', function (e) {
htmx.trigger($(this).closest('select').get(0), 'change')
})
})

最新更新