-3

How to make the below script pass the javascript values to the url of the href link?

<script type="text/javascript">
function myFunction(name) {
var elemA = name;


window.location.href = "view.php?search=elemA";

}
</script>

3
  • By concatenating a string and the content of your variable … window.location.href = "view.php?search=" + elemA; Commented Mar 10, 2020 at 10:26
  • (Should probably add proper URL encoding while you’re at it.) Commented Mar 10, 2020 at 10:27
  • Consider using template strings (back ticks `) Commented Mar 10, 2020 at 10:28

2 Answers 2

2

You can attach a variable to a string like this. You may have to use the function encodeURIComponent to avoid errors with whitespaces etc.

function myFunction(name) {
  var elemA = name;
  window.location.href = "view.php?search=" + encodeURIComponent(elemA);
}
Sign up to request clarification or add additional context in comments.

1 Comment

The correct function to use would be encodeURIComponent, applied on the parameter value only.
0

Use this...

window.location.href = "view.php?search="+elemA;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.