1

i have a <select> tag

i want redirect user onchange

i got an code and it works fine

the code is

<select onchange="if (this.value) window.location.href=this.value">
<option value="&s=1">1</option>
<option value="&s=2">2</option>
<option value="&s=3">3</option>
<option value="&s=4">4</option>
</select>

The problem here is :

The current link is: http://anlink.com/page.php?categ=4&subc=2

when i change option

i got redirected to http://anlink.com/&s=1

but i want it redirect to

http://anlink.com/page.php?categ=4&subc=2&s=1

So, i want edit the javascript code to something like this

if (this.value) window.location.href=
http://anlink.com/page.php?categ=4&subc=2 + this.value

i did not try this code but i think it will fail

2
  • Why not just change the option value from value="&s=3" to value="categ=4&subc=2&s=3" Commented Sep 1, 2012 at 3:25
  • @j08691 because i have a hundreds of options Commented Sep 1, 2012 at 3:37

2 Answers 2

2

This should work for you:

<script type="text/javascript">
function changeLocation(field) {
    loc = String(window.location);
    newLoc = loc.replace(/\&s=\d$/gi, "") + field.value;
    window.location = newLoc;
}   
</script>
<select onchange="changeLocation(this)">
<option value="&s=1">1</option>
<option value="&s=2">2</option>
<option value="&s=3">3</option>
<option value="&s=4">4</option>
</select>

It replaces any instance of &s= with a digit after it with nothing. Then it adds the new value. The reason for this is in case a &s= doesn't already exist.

If you would like the "s" value to change based on the "s" in the URL (i.e. when you load the page you have &s=3 in the URL, you want the select to be on "3" as well), make the following changes:

add onload="adjustS()" to the body

add an id to the select (I used "s")

add the following function:

function adjustS() {
    sLoc = String(String(window.location).match(/\&s=\d$/gi)).replace(/\&s=/gi, "");
    document.getElementById("s").selectedIndex = Number(sLoc)-1;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try with:

window.location.href += this.value

Edit:

var href = window.location.href;
var re = /&s\=\d$/;
if (re.test(href)) {
  window.location.href = href.replace(re, this.value);
} else {
  window.location.href += this.value;
}

4 Comments

This is a simple example, but you can check if the value is present first. Check edit.
why i don't just use something like this ((( if (this.value) window.location.href= mylink.com + this.value ))) Since the link does not change
i tried the code that i posted above, but i don't know why it does not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.