<select asp-for="ProductFilter.BrandId"
asp-items="@(new SelectList(Model.ProductFilter.Brands,"Id","Name"))">
<option>Chose one</option>
</select>
<button type="button" onclick="clearRadioButtons()" class="btn btn-outline-info mt-3">Clear</button>
我有一些串列項和 1 個默認項,即“選擇一個”,我想要的是當我單擊“清除”按鈕時,只需選擇串列選擇值“選擇一個”我如何使用 javascript 執行此操作?感謝您的幫助!
例如,我在選項中有 A、B、C、D,當然默認選擇一個,當有人選擇 C ??并單擊“清除”按鈕后,我想讓它回傳“選擇一個”。
uj5u.com熱心網友回復:
將空值添加到默認選項并添加 id 到 select 元素:
<select id="brand-select" asp-for="ProductFilter.BrandId" asp-items="@(new SelectList(Model.ProductFilter.Brands,"Id","Name"))">
<option value="">Chose one</option>
</select>
然后像這樣選擇默認選項:
function clearRadioButtons() {
var selectElement = document.getElementById("brand-select");
selectElement.value = "";
}
uj5u.com熱心網友回復:
為了滿足您的要求,我將提出兩種應該(或至少其中一種)適合您的解決方案。
選項 1:默認Form行為(讓瀏覽器為您解決問題)
對于這種情況,我寧愿使用元素的reset按鈕型別。form當瀏覽器加載頁面時,將所有button[type="reset"]表單欄位重置為其原始值。
這是一個示例,您可以從串列中選擇一個選項,然后單擊“重置”將串列恢復為原始狀態。
<form>
<select>
<option value="" selected>Choose</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<button type="reset">Reset</button>
</form>
all :* 請記住,
button[type="reset"]將嘗試將所有表單欄位重置為其原始值,而不僅僅是您的select元素。
注意:在上面的示例中,我有意使用屬性設定帶有文本“選擇”的
selected選項,以便選擇該選項,無論其在select元素中的位置如何。
選項 1:JavaScript解決方法
如果第一個解決方案無法使用,這里有一個依賴于解決問題的解決方案JavaScript。
這里的想法是通過為它指定一個默認選項ID(這樣我們可以通過 輕松檢索它JavaScript)和一個重置串列的按鈕上的事件偵聽器來設定默認選項。
const list = document.getElementById('list'),
defaultOption = document.getElementById('default-option'),
resetBtn = document.getElementById('reset-list');
// listen for "click" events on the "Reset" button
resetBtn.addEventListener('click', e => {
/**
* the below line is required only when you use a link (for example) instead of a button or the button type is different from "[type=button]".
/* The role of that line is to prevent the default behavior of the clicked element. In case of a link, the line prevents the unwanted jump on the page as the browser tries to follow the link and it scrolls the page all the way to the top (or simply follows the link if an "href" attribute is set on the "a" tag).
*/
e.preventDefault();
// reset the list
defaultOption.selected = !0;
});
<select id="list">
<option value="" id="default-option" selected>Choose</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<button type="button" id="reset-list">Reset</button>
我建議在單擊“重置”按鈕后使用要重新選擇的
selected屬性。option
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/503816.html
標籤:javascript html asp.net 核心
上一篇:如何用空白迭代字串?
下一篇:事件正在自動執行
