Redirect through the option value and keep it selected

1

I need to redirect according to the value of the "option" and keep this "option" selected after the redirect.

I can already redirect through this code:

$(function() {
// bind change event to select
$('#categoria').on('change', function() {
var url = "https://" + window.location.hostname + "/search?q=" + $(this).val();    // get selected value
if (url) { // require a URL
  window.location.href = url; // redirect
}
return false;
});
});

However, when redirected, the selected option remains the first in the list. I would like that after the redirect the selected option is selected.

I believe I could do this by requesting the option to "select" the option according to the value after the "=" parameter in the URL, but I am not sure how to do that.

Note: I only have access to HTML and Javascript, I do not have PHP (blogger host).

Edit 1: Let's say the URL is link and inside my code I have the following:

<select>
<option value="exemplo">exemplo</option>
<option value="exemplo2">exemplo</option>

So, because the Url parameter is "example" add the "selected" option, like this:

<select>
<option value="exemplo" selected>exemplo</option>
<option value="exemplo2">exemplo</option>
    
asked by anonymous 26.01.2018 / 00:40

1 answer

0

You can capture the value of the variable ?q= of the current URL and select the option with the same value:

var url_ = new URL(location.href);
var variavel = url_.searchParams.get("q");
$("#categoria").val(variavel); // #categoria é o ID do select
    
26.01.2018 / 01:03