簡體   English   中英

單選按鈕如何改變<option value="of a drop-down list in JS?">JS中的下拉列表?</option>

[英]How can a radio button change an <option> of a drop-down list in JS?

我的目標是讓單選按鈕更改<select>元素(下拉列表)的<option>

我已經能夠解決相反的行為(選擇另一個<option>會導致單選按鈕發生變化)。 正如你在這里看到的:

 function validate() { var x = document.getElementById("location_select"); var y = x.options[x.selectedIndex].value; { document.getElementById(y).checked = true; } }
 <select id="location_select" onchange="validate()"> <option value="berlin">Berlin</option> <option value="paris">Paris</option> </select> <label> <input type="radio" id="berlin" name="location"> <span>Berlin</span> </label> <label> <input type="radio" id="paris" name="location"> <span>Paris</span> </label>

現在我想生成相反的行為。 期望的行為:更改單選按鈕也會更改我選擇的<option>

單選按鈕 ID 與我的下拉選項的“值”相同。 因此 JS 變量可以用於 ID 以及“值”。

基本上,這是我目前的進展:

 function validate_2() { { document.getElementById("location_select").selectedIndex = "1"; } }
 <label> <input type="radio" id="berlin" name="location" onchange="validate_2()"> <span class="title">Berlin</span> </label> <label> <input type="radio" id="paris" name="location" onchange="validate_2()"> <span class="title">Paris</span> </label> <select id="location_select"> <option value="berlin">Berlin</option> <option value="paris">Paris</option> </select>
如您所見,目前只有 static。
如果這不是一個好方法,我願意接受更好的方法。

 function validate_2(city) { document.getElementById("location_select").value = city; } function validate_1(){ radio = document.getElementsByTagName('input') if(radio[0].checked)radio[1].checked = true else if (radio[1].checked)radio[0].checked = true }
 <label> <input type="radio" id="berlin" name="location" onchange="validate_2('berlin')" checked> <span class="title">Berlin</span> </label> <label> <input type="radio" id="paris" name="location" onchange="validate_2('paris')"> <span class="title">Paris</span> </label> <select id="location_select" onChange="validate_1()"> <option value="berlin">Berlin</option> <option value="paris">Paris</option> </select>

這個 function 可以通過更改radio輸入來更改<select>的選定選項

獲取已更改的無線電輸入的id並設置<select>標簽的value屬性

版本 1

function validate_2() {
    checkedVal = event.target.id;
    locationSelect = document.getElementById("location_select");
        
    locationSelect.value = checkedVal;
}

版本 2

它可以縮短為

function validate_2() {
    // ID becomes variable in JS
    location_select.value = event.target.id;
}

版本 3

顯式使用selectedIndex

function validate_2() {
    checkedVal = event.target.id;
    locationSelect = document.getElementById("location_select"); 
    indexToSelect = Array.from(locationSelect.options).findIndex(opt => opt.value == checkedVal);
    locationSelect.selectedIndex = indexToSelect;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM