4

Right now if I have multiple links using:

Options 1:
<a href="javascript:;" onClick="window.location.hash+='A'">Option A</a>
<a href="javascript:;" onClick="window.location.hash+='B'">Option B</a>
<a href="javascript:;" onClick="window.location.hash+='C'">Option B</a>

Options 2:
<a href="javascript:;" onClick="window.location.hash+='1'">Option 1</a>
<a href="javascript:;" onClick="window.location.hash+='2'">Option 2</a>
<a href="javascript:;" onClick="window.location.hash+='3'">Option 3</a>

Options 3:
<a href="javascript:;" onClick="window.location.hash+='X'">Option X</a>
<a href="javascript:;" onClick="window.location.hash+='Y'">Option Y</a>
<a href="javascript:;" onClick="window.location.hash+='Z'">Option Z</a>

Whenever clicking any of these, it will keep adding to the URL. Is there a way to check if a current hash already exists (ie. if third character in hash string, then replace with current hash). Any help would be great thanks! I'm trying to accomplish an end result which looks like below even if the user went back and forth between selecting options:

http://mydomain.com/question-page#A3Y 

1 Answer 1

3

change it to += to concatenate:

window.location.hash+='A';

I would do something like the following:

first, create variables for each of the possible options:

var option1 = "";
var option2 = "";
var option3 = "";

next, create a function that will set the hash:

function generateHash() {
  window.location.hash = option1 + option2 + option3;
}

finally, just set each of those options in the onclick event, as well as generating the hash:

<a href="javascript:;" onClick="option1 = 'A'; generateHash();">Option A</a> 
 ...
<a href="javascript:;" onClick="option2 = '1'; generateHash();">Option 1</a>
...
<a href="javascript:;" onClick="option3 = 'X'; generateHash();">Option X</a>
Sign up to request clarification or add additional context in comments.

5 Comments

that works, although is there a way to check for a current hash and replace if it exists? The problem is in my example above someone could select all 3 of an option and it'd just keep adding to the URL
then you should run that through a function that will do the replacing. side note, you have jquery tagged, but you don't have jquery in your post so you should remove that tag.
sorry, editted it out. I thought jquery might have a solution I needed.
i changed the answer, should be what you're looking for
This updated answer accomplishes exactly what I was trying to do, perfect. Huge thanks!

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.