HTML form input direct to URL - javascript

How do I direct the browser to another URL based on user input for example:
abc.com/apple.html
abc.com/banana.html
abc.com/pear.html
BUT, if the user doesn't enter apple,banana or pear then they are directed to:
abc.com/wrong.html
Any help would be awesome! I only know HTML forms.

<form id='formName' name='formName' onsubmit='redirect();return false;'>
<input type='text' id='userInput' name='userInput' value=''>
<input type='submit' name='submit' value='Submit'>
</form>
<script type='text/javascript'>
function redirect() {
var input = document.getElementById('userInput').value;
switch(input) {
case 'apple':
window.location.replace('apple.html');
break;
case 'banana':
window.location.replace('banana.html');
break;
default:
window.location.replace('default.html');
break;
}
}
</script>

You may use Javascript/JQuery to do it like this:
HTML:
<form name="form_input" action="post_values.php" method="post">
<input type="text" name="fruit" id="fruit" />
<input type="submit" value="Submit" />
</form>
JS/JQuery:
<script>
$("form").submit(function() {
var fruit = $("#fruit").val();
if(fruit=='apple' || fruit=='pear' || fruit=='banana'){
window.location = "http://www.abc.com/"+fruit+".html";
}else{
window.location = "http://www.abc.com/wrong.html";
}
return true;
});
</script>

In the HTML file of "abc.com", which is mostly index.html, between your <HEAD> tags do this:
<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.abc.com/wrong.html">
Adjust content= to how many seconds you want your browser to wait before redirecting.
Update:
The http method is not recommended by W3C because of this:
If a page redirects too quickly (less than 2-3 seconds), using the "Back" button on the next page may cause some browsers to move back to the redirecting page, whereupon the redirect will occur again. This is bad for usability, as this may cause a reader to be "stuck" on the last website.
Hence the recommended method via JS:
<head>
<script>
function replaceDoc()
{
window.location.replace("http://www.abc.com/wrong.html")
}
</script>
</head>
I found the above method here:
W3Schools Window.Replace()

<script language="JavaScript">
var page = new Array("apple","banana","pear"); // list of your pages
function redirect(){
if(page.indexOf(document.forms["NameOfForm"]["NameOfInput"].value)!=-1){
window.location = document.forms["NameOfForm"]["NameOfInput"].value + ".html";
}
else {
window.location = "wrong.html";
}
return false;
}
</script>
<form name="NameOfForm" onsubmit="return redirect()">
<input name="NameOfInput" />
<input type="submit" />
</form>
put that code into abc.com/ and you just have to add, change the list of page ;)

Related

javascript not working for URL re-direct

Can anyone help me with this script I'm trying to get working? I need a text box with a submit button, when a certain id is entered I need them to be re-directed to a certain site (below examples in the script are are yahoo, bing, etc).
This below is what I have so far, but the submit button doesn't show up and when the submit button is hit it doesn't seem to execute the script.
I just get a #? added to the url... I'm working in opencart so I think part of the problem might be with opencart.
<html>
<head>
<script>
document.getElementById("gobutton").addEventListener("click", function(event){
event.preventDefault()
var idmap={
REDDIT:"http://reddit.com",
YAHOO:"http://yahoo.com",
BING:"http://bing.com"
};
id=document.getElementById("siteid").value;
if (id in idmap) {
alert("going to "+idmap[id]);
window.location.href=idmap[id];
} else {
alert("invalid code ["+id+"]")
}
event.preventDefault()
});
</Script>
</Head>
<Body>
<form id="urllauncher" action='#'>
<label for="siteid">Site id</label>
<input type="text" id="siteid">
<button type="submit" id="gobutton">Go</button>
</form>
</Body>
</Html>
Thanks for any help on this!
You should add your script at the end of the body.
You are calling document.getElementById("gobutton").addEventListener too early, at this point the button is not yet present in the page DOM, so no event is attached to it.
Working code :
<html>
<body>
<form id="urllauncher" action='#'>
<label for="siteid">Site id</label>
<input type="text" id="siteid">
<button type="submit" id="gobutton">Go</button>
</form>
<script>
document.getElementById("gobutton").addEventListener("click", function(event){
event.preventDefault()
var idmap = {
REDDIT:"http://reddit.com",
YAHOO:"http://yahoo.com",
BING:"http://bing.com"
};
var id = document.getElementById("siteid").value;
if(id in idmap) {
alert("going to "+idmap[id]);
window.location.href=idmap[id];
} else {
alert("invalid code ["+id+"]")
}
});
</script>
</body>
</html>
PS : try to indent your code prior to posting it !
I think if you remove that form tag ,it will solve all your problems.
I think there's no need for it be of submit type and have a form at all
Just remove those and the event.preventDefault()

JS redirecting url changed

I have an input which on submit is redirecting to another page and i want this page to redirect to another using form input:
<form id="composeLink" method="post" name="composeLink" action="{$address}/" >
<input type="hidden" name="username" value="{$fields['username']}" />
<input type="hidden" name="password" value="{$fields['password']}" />
<input type="hidden" name="login" value="1" />
</form>
<script type="text/javascript">
//document.form.action = document.form.action.replace("http","https");
document.getElementById('composeLink').submit();
</script>
Action method of this form is send using smarty. The problem is that the link is not correct. Eg: current link is http://test.com and form action is http://action.com and the redirecting page has the link combined.
LE: the action form is send correctly
What can be the problem?
Problem is on your template engine, there is no problem, i mean on html. But you can write a javascript and solve that problem. If your action generated like that ( test.com/http://action.com ), please write this one :
<script type="text/javascript">
var newAction = document.getElementById("composeLink").action.split("http://");
document.getElementById("composeLink").action = "http://" + newAction[1];
document.getElementById('composeLink').submit();
</script>
If your action generated like that ( http://test.com/http://action.com ), please write this one :
<script type="text/javascript">
var newAction = document.getElementById("composeLink").action.split("http://");
document.getElementById("composeLink").action = "http://" + newAction[2];
document.getElementById('composeLink').submit();
</script>
The different is your generated URL, if there is two "http" on your URL (For split), you have to use last code as i wrote

Onclick Redirect Not Firing

I'm trying to redirect a user to another page after clicking on a form submit button.
I'm trying to fire a few events which fill in certain parts of the form automatically then submit the form & finally redirect the user to another page.
Everything works expect the redirect. I have tried a few things but havent gotten the redirect to work after the form submits.
I also don't want to user to be redirected before the form has been successfully submitted.
Here is my code:
<form id="usp_form" method="post" enctype="multipart/form-data" action="">
<input class="usp_input" type="text" name="user-submitted-title" id="user-submitted-title" value="" />
<input class="usp_input" type="text" name="user-submitted-url" id="user-submitted-url" value="">
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="">
<input class="usp_input" type="text" name="user-submitted-category" id="user-submitted-category" value="">
<textarea class="usp_textarea" name="user-submitted-content" id="user-submitted-content" rows="5"></textarea>
<input class="hidden" type="hidden" name="user-submitted-name" value="<?php echo $current_user->user_login; ?>">
<input onClick="copyText();copyText2();copyText3();handleClick();" class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post">
</form>
<script language="javascript" type="text/javascript">
function copyText3() {
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
document.getElementById("user-submitted-title").value = output1 + ', ' + output2;
}
</script>
<script language="javascript" type="text/javascript">
function copyText2() {
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
var output3 = document.getElementById("template").innerHTML;
document.getElementById("user-submitted-tags").value = output1 + ', ' + output2 + ', ' + output3;
}
</script>
<script language="javascript" type="text/javascript">
function copyText() {
var output = document.getElementById("templatebody").innerHTML;
document.getElementById("user-submitted-content").value = output;
}
</script>
<script language="javascript" type="text/javascript">
function handleClick() {
window.location.href='http://website.com/';
}
</script>
The submit button will launch a request, but you are also defining a redirecting request on the button press, so one will override the other (I'm not sure which one, it may depend on the browser).
You may want to fire an Ajax request instead of the standard submit, and do the redirection only when you get the response from the Ajax request so you are sure no information was lost.
You should not code like is but register your functions on the event, outside de HTML (it's always better to separate your HTML, JS and CSS).
You can understand about events bubling here : http://javascript.info/tutorial/bubbling-and-capturing
If you just want to see your code working and don't validate your form, just add "return false ;" at the end of your onclick attribute.
Edit : Oups sorry, you want submit your form, then redirect. You can do this with ajax requests (see http://www.w3schools.com/xml/xml_http.asp) : you submit your form in ajax, then you redirect.
But IMO, It's a serverside behaviour : you probably have a dynamic language (Python, PHP, ASP... ?) which process your form submission. It's here you have to redirect after the process.

Function call repeating itself

I've just started JavaScript and I am facing a problem. I've written a script in which I am calling a function. I don't know why this script is calling itself twice.
The code is as below:
<html>
<head>
<script type="text/javascript">
var randomNo1 = Math.floor(Math.random()*10);
var randomNo2 = Math.floor(Math.random()*10);
window.onload = ask;
function ask()
{
alert("How much " + randomNo1 + " times " + randomNo2 + "?");
}
function question()
{
var product = randomNo1 * randomNo2;
var stdAnswer = document.getElementById('answer').value;
if(stdAnswer == product)
{
alert("Very good!")
//generate new nos
randomNo1 = Math.floor(Math.random()*10);
randomNo2 = Math.floor(Math.random()*10);
ask();
}
else
{
alert("No. Please try again.");
ask();
}
}
</script>
</head>
<body>
<form>
Enter answer: <input type="text" id="answer" />
<input type="submit" value="Check" onClick="question()" />
</form>
</body>
</html>
Add action="#" to your form, to avoid page being refreshed when form is submitted.
<form action="#">
Enter answer: <input type="text" id="answer" />
<input type="submit" value="Check" onClick="question()" />
</form>​
You call it twice, once at startup window.onload = ask; and once in question
[edit]
note too that you don't have a ; after the first alert() in question()
[/edit]
Because your button is a submit button. When clicked it runs click handlers (if specified), then posts the form. So you call ask() twice. One time in a click handler, and another time in a window.onload handler.
After this form is submitted, page simply reloads (because it has no associated action). And onload handler is fired again.
You can see it here: http://jsbin.com/ukusof.
Your form as no method nor action. When you click your submit button, the page refresh itself, thus firing ask again.
You're submitting the form, which loads the page again, so ask will be fired again on load.
You have a form with a submit button. With no action in the form, it resubmits the page. You can stop this with
<input type="submit" value="Check" onClick="question();return false" />

Calling Javascript from a html form

I am basing my question and example on Jason's answer in this question
I am trying to avoid using an eventListener, and just to call handleClick onsubmit, when the submit button is clicked.
Absolutely nothing happens with the code I have.
Why is handleClick not being called?
<html>
<head>
<script type="text/javascript">
function getRadioButtonValue(rbutton)
{
for (var i = 0; i < rbutton.length; ++i)
{
if (rbutton[i].checked)
return rbutton[i].value;
}
return null;
}
function handleClick(event)
{
alert("Favorite weird creature: "+getRadioButtonValue(this["whichThing"]));
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="myform" onSubmit="JavaScript:handleClick()">
<input name="Submit" type="submit" value="Update" onClick="JavaScript:handleClick()"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
</body>
</html>
edit:
Please do not suggest a framework as a solution.
Here are the relevant changes I have made to the code, which results in the same behavior.
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.myform['whichThing'])));
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="aye">;
<input name="Submit" type="submit" value="Update" action="JavaScript:handleClick()"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
You can either use javascript url form with
<form action="javascript:handleClick()">
Or use onSubmit event handler
<form onSubmit="return handleClick()">
In the later form, if you return false from the handleClick it will prevent the normal submision procedure. Return true if you want the browser to follow normal submision procedure.
Your onSubmit event handler in the button also fails because of the Javascript: part
EDIT:
I just tried this code and it works:
<html>
<head>
<script type="text/javascript">
function handleIt() {
alert("hello");
}
</script>
</head>
<body>
<form name="myform" action="javascript:handleIt()">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>
In this bit of code:
getRadioButtonValue(this["whichThing"]))
you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.
EDIT
To get the value out of the radio buttons, grab the JQuery library, and then use this:
$('input[name=whichThing]:checked').val()
Edit 2
Due to the desire to reinvent the wheel, here's non-Jquery code:
var t = '';
for (i=0; i<document.myform.whichThing.length; i++) {
if (document.myform.whichThing[i].checked==true) {
t = t + document.myform.whichThing[i].value;
}
}
or, basically, modify the original line of code to read thusly:
getRadioButtonValue(document.myform.whichThing))
Edit 3
Here's your homework:
function handleClick() {
alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
//event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="aye" onSubmit="return handleClick()">
<input name="Submit" type="submit" value="Update" />
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.
In the function itself, I modified the how the form was being accessed. The structure is:
document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.
The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.
EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.
See the difference in this method:
function handleClick() {
alert("Direct Access: " + document.aye["whichThing"]);
alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
return false; // prevent further bubbling of event
}
Pretty example by Miquel (#32) should be refilled:
<html>
<head>
<script type="text/javascript">
function handleIt(txt) { // txt == content of form input
alert("Entered value: " + txt);
}
</script>
</head>
<body>
<!-- javascript function in form action must have a parameter. This
parameter contains a value of named input -->
<form name="myform" action="javascript:handleIt(lastname.value)">
<input type="text" name="lastname" id="lastname" maxlength="40">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>
And the form should have:
<form name="myform" action="javascript:handleIt(lastname.value)">
There are a few things to change in your edited version:
You've taken the suggestion of using document.myform['whichThing'] a bit too literally. Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].
There's no such thing as an action attribute for the <input> tag. Use onclick instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Obtaining and cancelling an Event object in a browser is a very involved process. It varies a lot by browser type and version. IE and Firefox handle these things very differently, so a simple event.preventDefault() won't work... in fact, the event variable probably won't even be defined because this is an onclick handler from a tag. This is why Stephen above is trying so hard to suggest a framework. I realize you want to know the mechanics, and I recommend google for that. In this case, as a simple workaround, use return false in the onclick tag as in number 2 above (or return false from the function as stephen suggested).
Because of #3, get rid of everything not the alert statement in your handler.
The code should now look like:
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
}
</script>
</head>
<body>
<form name="aye">
<input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
Everything seems to be perfect in your code except the fact that handleClick() isn't working because this function lacks a parameter in its function call invocation(but the function definition within has an argument which makes a function mismatch to occur).
The following is a sample working code for calculating all semester's total marks and corresponding grade. It demonstrates the use of a JavaScript function(call) within a html file and also solves the problem you are facing.
<!DOCTYPE html>
<html>
<head>
<title> Semester Results </title>
</head>
<body>
<h1> Semester Marks </h1> <br>
<script type = "text/javascript">
function checkMarks(total)
{
document.write("<h1> Final Result !!! </h1><br>");
document.write("Total Marks = " + total + "<br><br>");
var avg = total / 6.0;
document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
if(avg >= 90)
document.write("Grade = A");
else if(avg >= 80)
document.write("Grade = B");
else if(avg >= 70)
document.write("Grade = C");
else if(avg >= 60)
document.write("Grade = D");
else if(avg >= 50)
document.write("Grade = Pass");
else
document.write("Grade = Fail");
}
</script>
<form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
Semester 1: <input type = "text" id = "s1"/> <br><br>
Semester 2: <input type = "text" id = "s2"/> <br><br>
Semester 3: <input type = "text" id = "s3"/> <br><br>
Semester 4: <input type = "text" id = "s4"/> <br><br>
Semester 5: <input type = "text" id = "s5"/> <br><br>
Semester 6: <input type = "text" id = "s6"/> <br><br><br>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
Remove javascript: from onclick=".., onsubmit=".. declarations
javascript: prefix is used only in href="" or similar attributes (not events related)

Categories