获取当前URL并更新URL中的参数

问题描述

谢谢您的时间。

我正在尝试从URL中获取值并自动填写单选选项。

示例URL = https://example.com/v2-search/?&orderBy=relevance&tags=Kinship

<form action="https://example.com/v2-search/?" method="GET" >
    <div class="uk-inline">
        
        <div class="uk-inline">

           <label>Filter by: <label> 
           <input id="distance" class="uk-radio" type="radio" name="orderBy" value="distance"> distance 
            <input id="relevance" class="uk-radio" type="radio" name="orderBy" value="relevance" > Relevance 

        </div>
        
        <div class="uk-inline">
        <button style="margin-left: 15px;" class="uk-button uk-button-primary uk-button-small uk-mobile-width">Update</button>
    </div>

    </div>

</form>

这是我正在使用的带有注释的JS。

function autoFill() {
  var ob = url.searchParams.get("orderBy"); //Getting the value from the URL for the first radio options selected.
  var radioElements = document.getElementsByName("orderBy"); //Selecting the first radio options.

  for (var i=0; i<radioElements.length; i++) {
    if (radioElements[i].getAttribute('value') == 'ob') {
      radioElements[i].checked = true; //Adding checked to the value based on the URL
    }
  }
} 

解决方法

您可以将URL查询(搜索)字符串解析为URLSearchParams实例,这使得获取值更加容易。

然后您可以搜索相关的单选按钮并检查是否存在

const params = new URLSearchParams(location.search)
const orderBy = params.get("orderBy")

const radio = document.querySelector(`input[name="orderby"][value="${orderBy}"]`)
if (radio) {
  radio.checked = true
}