0

In my code bellow I would like to replace the string #customer with window.location.hash.

echo '<th><a href="?sort-by=email&order='. $this->order .'#customer">E-Mail</a></th>';

How would it be possible to mix JavaScript with PHP in my case?

1 Answer 1

3

This isn't really a matter of PHP.

Just remove the hash as it is right now in the PHP, then we can take it client-side and you can add it there. For instance, you'd make your PHP like this instead:

echo '<th><a href="?sort-by=email&order='. $this->order .'">E-Mail</a></th>';

(Simply removing the hash)

Then in JavaScript, we'd do this:

Element.href = Element.href + window.location.hash;

Where Element is the DOM selector method for the <a> tag.

EDIT Or if you have jQuery handy:

$("a").each(function(){
  $(this).attr("href", 
    $(this).attr("href") + window.location.hash
  )
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, how comes your jQuery code works when the selector is a but not if I want it to be a class name?
It doesn't? Are you sure you're doing the selector right? E.g. "a.hashed" or ".hashed"?
@RezaSaadati, Strange. It appears to work for me in this JSFiddle. (using .html() instead for visual reasons)
I noticed that this has nothing to do with your code. I even tried $(".myClass").click(function() { alert('test'); }); and there's nothing happening when I click that item. Not even an error. I will need to figure out what's wrong but thanks anyway for your great answer!

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.