2

I have this code that adds ?prside=5 for example. However, if you change this and the url already is &prside=5, it just appends it again (&prside=5&prside=40).

How do i update it instead of appending it, if it's already present?

<select name="prside" onchange="document.location.href = document.location.href + \'&prside=\' + this.value">
    <option>Annoncer pr. side</option>
    <option value="5">5</option>
    <option value="10">10</option>
    <option value="20">20</option>
    <option value="40">40</option>
</select>

EDIT: There is other GET variables in the real URL too. And the above script does work, it's just not very pretty with multiple &prside

Patrick Reck
  • 11,246
  • 11
  • 53
  • 86

1 Answers1

1

You could check for the existence of prside using the string indexOf method, then you could use a regular expression to replace the value if it exists:

href = document.location.href;
if(!~href.indexOf('prside'))
    document.location.href = href + 'prside=' + this.value;
else
    document.location.href = href.replace(/(prside=)\d+/, '$1' + this.value)

Here is a one liner if you want to put it straight into the HTML

document.location.href = !~document.location.href.indexOf('prside') ? document.location.href + 'prside=' + this.value : document.location.href.replace(/(prside=)\d+/, '$1' + this.value);
Ryan Lynch
  • 7,676
  • 1
  • 24
  • 33
  • This is the base URL: alpha_1/?side=annoncer When i copy/paste your oneliner, it doesn't do anything if &prside isn't already set. When it IS set (manually), this is what i get: alpha_1/?side=annoncer&prside=5prside=20 – Patrick Reck Aug 28 '12 at 14:47
  • Try it now. I chanced `~` to `!~` – Ryan Lynch Aug 28 '12 at 14:52