Below is a code that redirects people to a page of the same name. For example, if I type in the word 'chocolate' and click 'Submit', the user should be redirected to a page of the same name called 'chocolate.html', etc.
This code only works when the <form> parameter tag is removed, and if removed involves manually clicking the [Submit] button to be redirected to the .html page of the same name (rather than redirecting when prestting [Enter] or [Return] key on the keyboard).
This code does not work when I add the <form> parameter tag; it only works if removed. I've been meddling with this for hours to get it to work with the <form> tag. Any ideas?
This is the code:
Note: If you remove the form tag, it works, but only when you click the 'Submit' button manually.
<form>
<input id="test" type="text" autofocus>
<button onclick="redirect()">Submit</button>
</form>
<script>
function redirect()
{
var url=document.getElementById('test').value
window.location.href=url ".html"
}
</script>
CodePudding user response:
Add a type attribute to your button like so:
<button type="button" onclick="redirect()">Submit</button>
By default, if not set, the type of a button is assumed to be submit and will therefore submit your form to the action provided in the form's action attribute. Setting the type attribute to button prevents this default behaviour.
Seeing that you have no action attribute specified in your form, the current page is assumed as the action to redirect to so the form essentially reloads the current page.
CodePudding user response:
This is something new. Anyway the thing is when you are keeping the form tag there it is with no action attribute keeping you in the same page. When form tag is there you can not hit the script for the redirect.
When you are removing the form tag it is hitting the JS and activating the code. Seeing the form tag I am assuming that you are trying to send some data.
It is advised that you use jquery and ajax to manipulate these data. Or you can discuss more.
CodePudding user response:
Add this after your function:
var test_keydown = document.getElementById("test");
test_keydown.addEventListener("keydown", function (e) {
if (e.code === "Enter") { //checks whether the pressed key is "Enter"
redirect();
}
});
