我正在尝试<select>
用现有表单中的 Select2 替换标准。表单逻辑是用 Vanilla JS 编写的,客户端验证留给浏览器。
问题是当我使用 Select2 组件时浏览器生成的错误消息的位置:
document.querySelectorAll("[data-is=select2]").forEach(el => {
// the Select2 component only works with JQuery objects
let $jqo = $(el);
$jqo.select2({
width: "auto",
placeholder: el.firstElementChild.textContent
});
// making sure select2 works with the existing handlers
$jqo.on("select2:select", ev => el.dispatchEvent(new Event("change")));
});
form {
width: 20rem;
}
label {
display: flex;
align-items: center;
column-gap: 1ch;
}
/* making select and Select2 occupy the remaining space */
select, .select2-container {
flex-grow: 1;
}
<script src="https://code.jquery.com/jquery-3.7.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<!-- Standard select example --!>
<form>
<p>
<label>
Greetings:
<select name="greetings" required>
<option hidden disabled value="" selected>Select a Greetings</option>
</select>
</label>
<p>
<input type="submit" value="Standard select">
</form>
<hr>
<!-- Standard select replaced with a Select2 component !-->
<form>
<p>
<label>
Greetings:
<select data-is="select2" name="greetings" required>
<option hidden disabled value="" selected>Select2 a Greetings</option>
</select>
</label>
<p>
<input type="submit" value="Select2 select">
</form>
如您所见,单击按钮后,Select2 的验证消息被放置在<label>
而不是 下方<select>
。
我该如何修复它?最好不使用 JQuery。
应用
label { display: inline-grid; }
,并稍微定位<select>
: