Redirect through the option value and keep the option selected

Asked

Viewed 158 times

1

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

I can 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 at the top of the list. I would like that, after the redirect is selected the option chosen.

I believe I could do this by requesting that the option "select" be added to the option according to the value after the parameter "=" in the URL, but I have no knowledge of how to do this.

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

Edit 1: Let’s say the URL is http://www.dominio.com/search?q=exemplo and within 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" in the option, like this:

<select>
<option value="exemplo" selected>exemplo</option>
<option value="exemplo2">exemplo</option>
  • If you are redirecting, you will leave the page, no?

  • So your question isn’t explaining what you really want. If you leave the page, you won’t see the select anymore.

  • Yes, I look for if there is a script that can use a parameter to add an option in the option. Ex: If the url is: domain.com/search? q=example and have an option with value example it adds "Selected" in the code.

  • I added an "edit1" to the question, I guess I couldn’t explain it properly.

1 answer

0


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

var url_ = new URL(location.href);
var variavel = url_.searchParams.get("q");
$("#categoria").val(variavel); // #categoria é o ID do select
  • It worked out! Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.