Alaa Gamal
Alaa Gamal

Reputation: 1125

how to append something to javascript variable

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

Upvotes: 1

Views: 235

Answers (2)

Rhyono
Rhyono

Reputation: 2468

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;
}

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

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;
}

Upvotes: 0

Related Questions