Javascript redirect page

Hi,
i need to check a value of an input text in an html form, using javascript. When i press the submit button, If the value is a, then it goes to page a.html, if the value is b, then go to b.html page. How can i i do this?

Can anyone help?
Thanks

There are probably simpler ways to do this, but this way hopefully you can see what’s going on and can change it and extend it if you need to.

<input type="text" id="page-url" />
<button id="submit-it">GO!</button>

<script>
    // get the Submit Button Element
    var subBtn = document.getElementById('submit-it'); 

    // get the Input Element
    var pageUrl = document.getElementById('page-url'); 

    // Listen for the button to be clicked
    subBtn.addEventListener('click', function() {
      // simulate clicking a link, add ".html" to the end of what's in the input value
      window.location.href = pageUrl.value + '.html'; 
    });
</script>
1 Like

My answer for his homework answer involves a form too.

Please specify the page to go to:
<form id="gotopage">
    <p><label>Name of page: <input name="pagename"/></label></p>
    <p><input type="submit" value="Go to page"/></p>
</form>
<script>
document.querySelector('#gotopage').onsubmit = function (evt) {
    evt.preventDefault();

    var form = this;
    location.href = form.elements.pagename.value + '.html';
}
</script>

Put in a and you will be taken to a.html, and b goes to b.html

1 Like

Oh no! But what if they want older browsers to be supported! Or are teaching from old course material?

The following helps to fill that gap:

<form onSubmit="javascript:location.href = pagename.value + '.html'; return false">
    <label for="pagename">Name of page: </label><input id="pagename" name="pagename"/><br>
    <input type="submit" value="Go to page"/>
</form>

That’s the only time you need code that old now. The most recent browser you’d actually need that code for is Netscape 4. The other examples supplied will not work in IE8 or earlier but there are workarounds that would get them working for all other browsers more recent than Netscape 4.

If it is a history of JavaScript course then that code probably is the expected solution.

lol I didn’t even recognize it as homework. I can see it now.

Oh well.

lol, it was not a homework :slight_smile: but it could be!
also, not from old school material, actually i think the first Paul_Wilkins material will do it.
One question , coulf i put that script in a js. file?
Is so, i only need to call it in the head?
Thank you very much, i’ll try and give feedback in a second.
mrseo

Putting it in the head is old-school and results in further problems.

It’s much better and safer to put it at the end of the body.

<html>
<head>...</head>
<body>
...
<script src="js/file.js"></script>
</body>
</html>

Thank you very much Paul, and everyone!
Best

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.