Problem when using Javascript to redirect user on form submit
I have a web page on which I have a form. This form contains a button and a textbox. When the button is clicked or when the form is submitted I would like to take the text from the text box and append it to a url. The code looks like this:
<form
name="askaquestion"
id="ask-a-question"
onSubmit="window.location.href='http://www.someurl.com/app/' + document.askaquestion.question_ask.value"
>
<input
type="submit"
name="submit_question"
value="Submit"
class="submit&qu开发者_如何学Cot;
onClick="window.location.href='http://www.someurl.com/app/' + document.askaquestion.question_ask.value"
/>
<input
type="text"
name="question_ask"
value="What's Your Question?"
class="inputsmall"
id="ask_us_a_question_textbox"
/>
</form>
The problem is that this works sometimes and sometimes it takes me to this URL:
http://dev/fs?submit_question=Submit&question_ask=help&hiddenInputToUpdateATBuffer_CommonToolkitScripts=1#
I am not sure why this is happening. The form is in a using jQuery to fade in and out, could this be an issue? Is there a better way of achieving the described behaviour?
Add return false;
to the onSubmit
:
onSubmit="window.location.href='http://www.someurl.com/app/' + document.askaquestion.question_ask.value; return false;"
This stops the form submission (that's why you got http://dev/fs?submit_question...
- which indicates that your page is named fs
).
When users click on the submit button, a "submit" action would be triggered, after performing the onClick action. To prevent the submit action from happening, you need to do what Gert said, return false on either <input onClick="return false">
or <form onSubmit="return false">
.
Why don't you just use <form action="http://www.someurl.com/app/">
, so the data would be sent to that url you specified?
If you really want the data to be sent to two different places, it's probably better to do the second set of requests in your first handler, i.e. what the form action specifies.
Some useful links:
http://www.w3schools.com/tags/tag_form.asp
http://bytes.com/topic/javascript/answers/809181-noobie-onclick-confirm-return-false
精彩评论