简体   繁体   English

单击时更改选择的选项

[英]Change selected option when clicked

What I am trying to achieve is as follows: 我要实现的目标如下:

When the user changes the selected value in the select box, it will refresh the page, add the selected text value to the existing URL and reset the select box default to the value selected by the user before page refresh. 当用户在选择框中更改选择的值时,它将刷新页面,将选择的文本值添加到现有URL,并将选择框默认值重置为用户在页面刷新之前选择的值。

Any ideas what I am doing wrong? 有什么想法我做错了吗?

HTML code: HTML代码:

<select class="selectedForm">
    <option value="one" selected>one</option>
    <option value="two">two</option>
    <option value="three">three</option>
    <option value="four">four</option>
</select>

Javascript code: JavaScript代码:

$(".selectedForm").change(function() {    
   $('.selectedForm option:contains(' + this.value + ')').prop({selected: true});    
   alert( $('.selectedForm').find(":selected").val() );
   if ( window.location.href.indexOf("&") > -1 )  {
       window.location.search = '?toWhere=Cursos&q='+$('.selectedForm').find(":selected").text();
   } else {
       window.location.search += '&q='+$('.selectedForm').find(":selected").text();
   }
});

FIDDLE 小提琴

From get-url-parameters-values-with-jquery , 带有jQuery的get-url-parameters-values值中

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

$(function(){
   var q= getUrlVars()["q"];
   if(q){
       $('.selectedForm option:contains('+q+')').prop('selected',true);
   }    
});

And if you are using server side script like PHP then, it is more easy to get by using $_GET or $_REQUEST 而且,如果您正在使用server side scriptPHP ,那么使用$_GET$_REQUEST会更容易

Also you can change your drop down onchange event like, 您也可以更改下拉onchange事件,例如,

$(".selectedForm").change(function () {
    if (window.location.href.indexOf("&") > -1) {
        window.location.search = '?toWhere=Cursos&q=' + $('.selectedForm option:selected').text();
    } else {
        window.location.search += '&q=' + $('.selectedForm option:selected').text();
    }
});

Something like that 像这样

To preserve the value of the selector after a reload you could use something like: 要在重新加载后保留选择器的值,可以使用以下方法:

$(".selectedForm").on('change', function() {
  var _loc = String(location.href)
      ,loc  = _loc.substr(0, _loc.lastIndexOf('/'));
      self.location.href = loc + '?selected='+this.value;
});

// handler to load the selected option on page load
function loadSelectedOpt() {
    var loc = location.search;
    if (loc.length) {
        $(".selectedForm").val(loc.split('=')[1]);
    }
}

In words: add the selected option value to the querystring of the current location ( ?selected=[selected value] ), reload the page, and use the querystring to set the value of the selector when the page is reloaded. 换句话说:将选定的选项值添加到当前位置的查询字符串( ?selected=[selected value] ),重新加载页面,并在重新加载页面时使用querystring设置选择器的值。

Here's a jsFiddle demo 这是一个jsFiddle演示

This can be done by storing the value in localstorage and on page loads you have to set the value again to the dropdown. 这可以通过将值存储在本地存储中来完成,并且在页面加载时,您必须再次将值设置为下拉列表。 This is the only way in front end. 这是前端的唯一方法。

Otherwise you can do this by sending the value to backend and getting back on page loads. 否则,您可以通过将值发送到后端并重新加载页面来实现。

Hope this will solve your problem!! 希望这能解决您的问题!

What you are missing here is after a page refresh, all resources are reloaded. 您缺少的是在刷新页面后重新加载所有资源。 Since the dropdown and your javascript is reloaded, this.value will not have a valid value that you are looking for to set the dropwdown. 由于下拉列表和JavaScript已重新加载,因此this.value将没有您要设置下拉菜单的有效值。

You can either use local storage or simply retrieve the previously selected value from your query string. 您可以使用本地存储,也可以只从查询字符串中检索先前选择的值。 Further, you will need to set it during load event of the page. 此外,您需要在页面的load事件期间进行设置。 Here is an example: 这是一个例子:

$(document).ready( function(){
    var queryStringBegin = window.location.search.indexOf("&q=");

    if ( queryStringBegin > -1 )  {
        var queryStrValue = window.location.search.substr(window.location.search.indexOf('&q=')+3);
        $('.selectedForm option:contains('+queryStrValue+')').prop({selected: true});
    }
});

NOTE: Further checks may be required in case '&q=' is not always the last section of the query string. 注意:如果'&q='并非始终是查询字符串的最后一部分,则可能需要进一步检查。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM