How to do something before on submit? - javascript

i have a form which has a button that submits the form. I need to do something before submits happen. I tried doing onClick on that button but it happens after the submit.
I can't share the code but, generally, what should I do in jQuery or JS to handle this?

If you have a form as such:
<form id="myform">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$('#myform').submit(function() {
// DO STUFF...
return true; // return false to cancel form action
});
Update; for newer JQuery versions (to avoid deprecation warnings), try:
$('#myform').on('submit', function() {
// ...
return true;
});

Assuming you have a form like this:
<form id="myForm" action="foo.php" method="post">
<input type="text" value="" />
<input type="submit" value="submit form" />
</form>
You can attach a onsubmit-event with jQuery like this:
$('#myForm').submit(function() {
alert('Handler for .submit() called.');
return false;
});
If you return false the form won't be submitted after the function, if you return true or nothing it will submit as usual.
See the jQuery documentation for more info.

You can use onclick to run some JavaScript or jQuery code before submitting the form like this:
<script type="text/javascript">
beforeSubmit = function(){
if (1 == 1){
//your before submit logic
}
$("#formid").submit();
}
</script>
<input type="button" value="Click" onclick="beforeSubmit();" />

make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.

Form:
<form id="formId" action="/" method="POST" onsubmit="prepareForm()">
<input type="text" value="" />
<input type="submit" value="Submit" />
</form>
Javascript file:
function prepareForm(event) {
event.preventDefault();
// Do something you need
document.getElementById("formId").requestSubmit();
}
Note: If you're supporting Safari (which you probably are) you'll need to pull in a polyfill for requestSubmit()

Related

jcryption form submit not working with button click

I am using jcryption for encrypting the form.It works fine if i use submit button in form. Instead if i use button and submit the form manually my jcryption method is not getting called.
below is my code
<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#login").bind('click', function(){
document.authenticatorform.username.value=$("#username").val();
document.authenticatorform.password.value=$("#password").val();
alert('outer hello');
$("#authenticatorform").jCryption({
getKeysURL:"<%=request.getContextPath()%>/keypairrequest",
beforeEncryption:function() {
alert('inner hello');
document.authenticatorform.submit()
return true; },
encryptionFinished:function(encryptedString, objectLength) {return true;}
});
});
});
</script>
<body>
<form:form method="post" action="login.htm" name="authenticatorform" id="authenticatorform">
<input type="hidden" name="username"/>
<input type="hidden" name="password"/>
</form:form>
<input type="button" id="login"/>
</body>
</html>
In the code only outer alert is printing.
Is it possible to call jcryption in other than submit button?
Any help will be greatly appreciated!!!!!
Try using on click function instead of bind
Try this:
$("#login").on('click', function(){
//your codes goes here
}

Is it possible to execute simple javascript statments from an input field in a document?

In the example below I've attached a function main to an input field. the function contains instructions to send an alert with a variable message (whatever the user enters into the field).
<form>
<input type="text" onsubmit="main()" />
<input type="submit" />
</form>
<script>
function main (param) {
alert(param)
}
//main();
</script>
It doesn't work, but I believe that's because I've made some noob error that I'm failing to recognize. The result of a functioning version of this code would be the ability to submit "hello world" and produce an alert box stating 'hello world' (without quotes).
But, further than this, I'd like to be able to pass the likes of main("hello world"); or just alert('hello world'); to the input field to produce the same result.
The problem I think I'm running into is that the page is refreshed every time I submit. There are a few questions on here with similar problems where people have suggested the use of onsubmit="main(); return false;", but in fact this does not seem to work.
Looks like you want to eval() the value of the input.
Use with caution, has security impact...
Returning false from a handler stops the regular action so you have no redirect after submitting:
<form onsubmit="main(); return false;">
<input id="eval-input" type="text" />
<input type="submit" />
</form>
<script>
function main () {
eval(document.getElementById('eval-input').value);
}
</script>
Here's how you can detect a form submission:
<form onsubmit="foo()">
<input type="text">
<input type="submit">
</form>
<script>
function foo(){
alert("function called");
}
</script>
I however advise you do this (preference), if you desire to manage the form data through a function:
<form id="myform">
<input type="text">
<input type="submit">
</form>
<script>
document.getElementById("myform").onsubmit=function(event){
alert("function called");
//manage form submission here, such as AJAX and validation
event.preventDefault(); //prevents a normal/double submission
return false; //also prevents normal/double a double submission
};
</script>
EDIT:
use eval() to execute a string as JavaScript.
jQuery way:
You create event listener which will be triggered when user click 'submit'.
<form>
<input type="text" id="text"/>
<input type="submit" />
</form>
<script>
$( "form" ).submit(function( event ) {
event.preventDefault();
alert( $('#text').val() );
});
</script>
To prevent page reloading - you should use event.preventDefault();
Pure JavaScript:
<form>
<input type="text" id="text"/>
<input type="submit" id="submit" />
</form>
<script>
var button = document.getElementById("submit");
var text = document.getElementById("text");
button.addEventListener("click",function(e){
alert(text.value);
},false);
</script>
If I understand what you want to do, you can call the function like this, and writing params[0].value you can access the input value:
function main(params) {
//dosomething;
document.write(params[0].value);
}
<form onsubmit="main(this)">
<input type="text">
<input type="submit">
</form>
Try something like this
onchange="main()"
onmouseenter, onMouseOver, onmouseleave ...
<input type="text" onmouseenter="main()" />

my jquery form validation is not working as i hope it should

I have some javascipt code here that validates a user form. When the user inputs the correct answer it tells them and gives them the link to the next question. At least, that's what it is supposed to do. When i click the form it reloads the page but it should not because i added return false.
the div tra holds 35
and the div usermsg is the user inputted value.
<script>
$("#submit").click(function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6<>rightanswer)
{
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else
{
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
</script>
Any ideas why this is not working?
It should be
if (clientmsg6 != rightanswer)
not
if (clientmsg6<>rightanswer)
To prevent a form submission, you need to return false on the form itself instead of on the submit button. Your code should become:
HTML
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="submit" value="Submit" />
</form>
JS (please note the line where you have clientmsg6, you have a syntax error)
$("#myform").on('submit', function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6 != rightanswer) { //This line was also wrong, should be != instead of <>
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else {
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
Alternatively, you can keep your existing code by changing your submit button to be just a plain old button, but you will lose the extra functionality of the user being able to hit the enter key and performing the same action.
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="button" value="Submit" />
</form>
Instead of using .html(), try using .text()
if #submit is a link tag otherwise use the form ID and the submit event
$("#submit").click(function(e){
e.preventDefault()
...
...
...
});
You need to attach handlers once the document has finished loading.
Wrap your script in the following
<script>
$(function() {
// script
});
</script>

Use html5 validations even if form is never being submitted?

What I am doing is catching the click action on my form's submit button, preventDefault()ing it, doing some computation, and then making an ajax call instead of submitting the form.
Is there a way to use javascript to force the html5 validators to fire even if the form isn't being submitted?
$('#submitButton').click(function (e) {
e.preventDefault(); //stop the form from submitting
//Do computation
$.post('/comments', values, function(results) {
hideForm($('#new_comment_' + parentId));
parent.children('.children').prepend(results);
}, 'html');
});
It works just fine, I tested in latest Chrome and Firefox. Just e.preventDefault() on the <form>:
html:
<form method="post" action="test.html">
<input type="text" required></input>
<input type="submit" value="Submit">
</form>
jQ:
$('form').submit(function(e){ e.preventDefault(); });
example: http://jsfiddle.net/elclanrs/2nnLc/2/
Using html5 constraints the form object has some new methods. For example you can call checkValidity() on the form object to check the input.
<form method="post" action="test.html" id="myForm">
<input type="text" required></input>
<input type="submit" value="Submit" id="submitButton">
</form>
<script type="text/javascript">
$('#submitButton').click(function (e) {
e.preventDefault();
alert($("#myForm").get()[0].checkValidity());
})
</script>

prevent form from submitting to a different page

I have this code:
<form method="get" action="" id="search">
<input id="search_box" name="search" type="text" class='search_box' onkeypress="if(event.keyCode==13) sentAjax('searchdata.php');var filelink='searchdata.php';" value="" onclick="this.value=''" />
<input type="hidden" name="course_val" id="course_val" />
</form>
I want to block the form from submitting to a different page.Now if you hit enter it submits to a different page
in pure javascript
<form method="get" action="" id="search" onsubmit="return false;">
...
</form>
Please note that will not let you submit the form so ideally you would invoke your submit handler function in which you would control when you want to submit
<form method="get" action="" id="search" onsubmit="return mySubmitHandler()">
...
</form>
and in your submit handler
function mySubmitHandler(){
if (submit_criteria_met) {
return true;
} else {
return false;
}
return false;
}
This should do the trick:
$('form#search').on('submit', function(e) {
e.preventDefault();
});
The important part being e.preventDefault(), which prevents the form submitting when it's submit event is triggered.
Remove the onkeypress attribute in the input field, it looks like it does some posting behind the curtains when pressing enter (keycode 13).
You might also want to prevent the form from submitting, although it seems to submit to the same page since the action attribute is empty.
If you are unable to edit the HTML, try something like:
$('#search').submit(function(e) {
e.preventDefault();
}).find('input[onkeypress]').removeAttr('onkeypress');
Test: http://jsfiddle.net/DAvfm/
Prevent the default action of the form.
$('#search').submit(function(event) { event.preventDefault(); });
$('#search').bind('submit',function(e) {
e.preventDefault();
});

Categories

Resources