I'm creating a site and have a text field where you can enter text and it will append itself to the url. Right now I have the system somewhat working however, a page won't show up.
Here is the code I have:
<script>
function changeText2() {
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "http://jwallach.prepdev.org/" + userInput;
window.location = "http://jwallach.prepdev.org/" + userInput;
}
</script>
Link <a href="" id=lnk>nothing </a>
<br>
<input type='text' id='userInput' value=' ' />
<input type='button' onclick='changeText2()' value='Change Link' />
However, the page cannot be found because of the %20 in front of the URL. How might I fix this? Site
Either remove the leading space from the input:
<input type='text' id='userInput'/>
...or trim the content:
function changeText2(){
var userInput = document.getElementById('userInput').value.trim();
var lnk = document.getElementById('lnk');
lnk.href = "http://jwallach.prepdev.org/" + userInput;
window.location = "http://jwallach.prepdev.org/" + userInput;
}
The latter is a better idea since leading/trailing spaces are a common mistake a user makes when typing/pasting in a field.
If the user isn't knowingly entering in part of a URL, you should also make sure to URL encode their input in case their input contains non-URL-safe characters:
lnk.href = "http://jwallach.prepdev.org/" + encodeURIComponent(userInput);
Simple, just remove the %20 from the input value. :)
So this..
<input type='text' id='userInput' value=' ' />
becomes this..
<input type='text' id='userInput' value='' />
Just change this: <input type='text' id='userInput' value=' ' />
to this: <input type='text' id='userInput'>
Due to the value
attribute, a space
or %20
was the default value inside the input tag. %20
is nothing just the ASCII encoding reference value of space
. Learn more about ASCII value reference here .
Either start typing the value after hitting backspace a couple of time, or just change value=" "
to value=""
or simply remove the value
attribute and it will solve the issue right away.
The %20
will pop again if the user hits space by mistake. So what you can do is, trim the input.
Make the following change in the your script tag.
<script>
function changeText2(){
var userInput = document.getElementById('userInput').value.trim();
var lnk = document.getElementById('lnk');
lnk.href = "http://jwallach.prepdev.org/" + userInput;
window.location = "http://jwallach.prepdev.org/" + userInput;
}
</script>
Hope it helps. :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.