2

I am learning Javascript and this might be a very stupid question but I am running nuts. I was trying all sort of things to prevent a form to be submitted with no luck so now I placed a very simple function that will always return false. Still the form is submitted, can someone explain why and what do I need to change? THANKS!

<form action="http://students.open.ac.uk/mct/tt284/reflect/reflect.php" method="post" name="displayTimeTable" onsubmit="return toSubmit();">

<some html>.....

<input type="submit" id="submit" name="submit" value="Submit" />

`

and the javascript

function toSubmit(){
  alert('I will not submit');
  return false;

}

9
  • have you closed the <form> tag using </form>?? Commented Dec 29, 2013 at 14:54
  • your code seems to be working perfect, See this FIDDLE >> Commented Dec 29, 2013 at 14:58
  • Just use Javascript to improve visitors experience. They might turn it off. So you need to also do validation at the server end. Commented Dec 29, 2013 at 15:00
  • I am using Fiddle since the beginning. The HTML tags are properly closed. Commented Dec 29, 2013 at 15:00
  • 1
    check your console for any errors Commented Dec 29, 2013 at 15:02

2 Answers 2

1

Try an onclick event on the submit button instead of onSubmit

<input type="submit" id="submit" name="submit" value="Submit" onclick="return toSubmit();"/>
Sign up to request clarification or add additional context in comments.

10 Comments

Change the type to 'button'.
@JoyAdamson can you create a fiddle at jsfiddle.net? A button can't submit the form by itself, it have to call the submit function. But in your case it must work with the submit button too.
@JoyAdamson i think there is the problem.. you are checking it in fiddle only rite?? in fiddle such script should be put in same frame where html is written, like this FIDDLE >>
@JoyAdamson see your fiddle now... The function will not work in the script frame. If moved it in the HTML block, it works now.
@JoyAdamson your fiddle didn't work because by default the scope is "onLoad" meaning whatever functions you write, they are local to the window onload event and can't be called from within buttons. See this updated fiddle where same code works after choosing "No wrap" option.
|
0

Working fine for me:

http://jsfiddle.net/acrashik/yQ2gL/1/

<script>
    var onSubmit = function() {
        return false;
    }
</script>
<form action="/" method="post" onsubmit="return onSubmit();">
<input type="submit" />
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.