1

I have the following code:

<script type="text/javascript"> function changeText2(){ var userInput = document.getElementById('userInput').value; var lnk = document.getElementById('lnk'); lnk.href = "www.google.com/search/" + userInput; lnk.innerHTML = lnk.href; } </script> Here is a link : <a href="" id=lnk>nothing here yet</a> <br> <input type='text' id='userInput' value=' ' /> <input type='button' onclick='changeText2()' value='Change Link'/> 

So, this basically does the following:

User enters a word in the text box, and that word is appended at the end of the link given (www.google.com/search/). And the link is displayed above on the page.

But instead of displaying the link on the page, I want it to open that page when the button is clicked. How can I do that?

1
  • In your first <a> tag, the id should be enclosed in quotation marks id="lnk" Commented Aug 26, 2015 at 16:17

3 Answers 3

1

See this fiddle

Try window.location to redirect to the page on click.

That is, in your code try like

<script type="text/javascript"> function changeText2(){ var userInput = document.getElementById('userInput').value; var lnk = document.getElementById('lnk'); lnk.href = "www.google.com/search/" + userInput; window.location = "www.google.com/search/" + userInput; } </script> 
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks @Lal but after I click the button then it does redirect to the new link but it also displays that link on the page for a second. How can I avoid that?
See my edited script. Remove lnk.innerHTML = lnk.href;.
Is it possible to make it work by pressing the 'enter' button also?
Try changing the input type to submit.
was you trying that in the above fiddle ?
|
0

You can change the current url by changing window.location

This would make your function look as follows:

function changeText2(){ var userInput = document.getElementById('userInput').value; var lnk = document.getElementById('lnk'); lnk.href = "www.google.com/search/" + userInput; lnk.innerHTML = lnk.href; window.location = lnk.href; } 

Comments

0

As pointed by others, you can use the location object in two ways

Replacing it

window.location.replace("http://url.to") 

or setting the href value

window.location.href = "http://url.to" 

You also need to encode the text input to make it url safe

window.location.href = "http://url.to/search?q="+encodeURIComponent("Query value") 

Also, it's important to include the protocol (http) if you are linking to an external domain.

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.