简体   繁体   中英

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"  
  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, ie 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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM