简体   繁体   English

如何检查 URL 中的查询并使下拉列表选择该值?

[英]How do I check a query in the URL and make a dropdown select that value?

Say for instance that my URL could have an appended query string (ie "&sort=").举例来说,我的 URL 可以附加一个查询字符串(即“&sort=”)。 How can I check for that query value and then make a drop-down list show the same selected value?如何检查该查询值,然后使下拉列表显示相同的选定值?

Example:例子:

URL could be: example.com/Pages/default.aspx?Type=2&sort=price URL 可以是:example.com/Pages/default.aspx?Type=2&sort=price

or sort may not exist if nothing has been selected.如果未选择任何内容,则或排序可能不存在。

<select name="SortBy" id="SortBy">
  <option selected="selected" value="Item Number">Item Number</option>
  <option value="Price">Price</option>
  <option value="Weight">Weight</option>
  <option value="Date">Date</option>
</select>

I need to take that sort value in the URL and set instead:我需要在 URL 中采用该排序值并进行设置:

<select name="SortBy" id="SortBy">
  <option value="Item Number">Item Number</option>
  <option selected="selected" value="Price">Price</option>
  <option value="Weight">Weight</option>
  <option value="Date">Date</option>
</select>

Thanks.谢谢。

// check for query parameters
if (window.location.search){
  // grab the `sort=foo` portion
  var sort = window.location.search.match(/sort=([^&]+)/);
  // check if it's there
  if (sort){
    // get the value portion
    var sortValue = sort[1].toLowerCase();
    // because there's a potential cASe difference, iterate over the options
    // and mark the matching entry based on value
    $('#SortBy option').each(function(){
      var $option = $(this);
      if ($option.prop('value').toLowerCase() == sortValue){
        $option.attr('selected','selected');
        return false; // "break;"
      }
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何进行下拉多选? - How do I make a dropdown multi select? 如何在单击时使Bootstrap Select2下拉列表转到所选的URL? - How do I make Bootstrap Select2 dropdown go to the selected URL on click? 如何使拨动开关触发 select 下拉菜单以随机化其选项值? - How do I make a toggle switch trigger a select dropdown to randomize its option value? 我如何使用for循环使.append <select>落下 - How do i make an .append using a for loop in a <select> dropdown JavaScript-如何执行下拉选择中的某些查询? - JavaScript - How do I execute certain query from dropdown select? 如何获得下拉菜单的当前选定值(选择标记) - How do I get the currently selected value of dropdown (select tag) 如何在垫选择下拉列表中填充现有值? - How do I populate existing value in a mat-select dropdown? 如何通过使用javascript在MVC中选择下拉列表的值? - How do I select a value of a dropdown in MVC by using javascript? 使用 jQuery,如何获得特定的下拉元素(<select></select> ) 基于下拉列表的值? - Using jQuery, how do I get a specific dropdown element (<select></select>) based on the value of the dropdown? 如果 URL 与值匹配,如何选择下拉列表? - How to make dropdown selected if URL matched with value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM