triggering a form onsubmit using an anchor - javascript

I have a form which has a cancel button, a save (submit) button and a save continue link. Now the buttons work and the javascript is called via a function called from the form onsubmit method. This works as expected as does the cancel button. however the save and continue is not working. Follows is a simplified example:
<form id="save-form" class="admin-form" method="post" action="save-job" onsubmit="return jobFormSave(this);">
<input type="text" name="data" value="">
← cancel
<input class="button" type="submit" value="save">
<a class="button oklink" onclick="document.getElementById('save-form').submit();">ok →</a>
</form>
And the javascript for simplification just alerts ok (the real example has an ajax call to the save-job action):
<script>
window.jobFormSave = function (aForm) {
alert( "Ok" );
}
</script>
So when i click Save button the form is validated, saved and a message is displayed. Clicking on the Ok link however triggers the form submit action (save-job) but i want it to use the jobFormSave function. So I've a few questions:
can this be done while submitting the form data to the function?
can i determine whether i clicked the ok or the save button from within the javascript (or if not within the save-job action function)?
Is there a better way to achieve what seems an everyday thing.
I'm using php 7.2 to handle the forms action functionality and jQuery is available and used for the ajax query in the actual code.
I've kept the code short as mostly it is not relevent to the question but I can provide more code if you guys need it.

Probably you are looking for:
<script>
window.jobFormSave = function (aForm, action) {
alert('User '+ action + " form with data "+ JSON.stringify(aForm))
if (action == 'okayed')
aForm.submit();
}
</script>
<form id="save-form" class="admin-form" method="post" action="save-job" onsubmit="return jobFormSave(this, 'submitted');">
<input type="text" name="data" value="">
← cancel
<input class="button" type="submit" value="save">
<a class="button oklink" href="javascript:{}" onclick="return jobFormSave(document.getElementById('save-form'), 'okayed');">ok →</a>
</form>
Form can be passed as an argument as I did in anchor tag's onclick and then it can be decided to submit at function level based on the action

Related

jquery prevent reload form on submit

I want to upload files using javascript/jquery/ajax and in my case, I have to prevent the reload on form submitting on upload.
Also, I want to add a delete button, such that, when file is uploaded, the delete button can delete this and same is the scenario, that to prevent the page refresh/reload on form submitting.
Hence, I've three buttons in a single form, UPLOAD, DELETE, NEXT and in my case, only next allows to submit the form by refreshing/action of form. And obviously, when file is just selected and the user directly hits the next button, it first uploads and then take his action.
HTML:
<form name="myform" method="post" id="FORM2" enctype="multipart/form-data">
// OTHER VALUES OF FORM
<input type="file" name="FileUpload-1" id="FileUpload-1" class="file_upload" />
<input type="submit" value="Upload" id="upload" class="submitUpload" />
<input type="submit" value="Delete" id="delete" class="submitDelete" />
<input type="submit" name="" id="FORMSUBMIT">
</form>
JS:
$(".submitUpload").click(function(){ console.log('UPLOAD');
action = "upload.php";
$("#FORM").on('submit',function(){
var options={
url : action,
success : onsuccess
};
$(this).ajaxSubmit(options);
return false;
});
}
return false;
});
$(".submitDelete").click(function(){ console.log('DELETE');
return false;
});
$('.FORMSUBMIT').click(function () {
//CUSTOM HANDLING
});
To Directly answer your question:
$("#FORM").on('submit',function(evt){
evt.preventDefault();
});
This piece of code will prevent the normal form submitting.
My advice is to transform the Update and Delete buttons from type=submit to type=button. Like this:
<input type="button" value="Delete" id="Delete" class="submitDelete" />
This will prevent the form to be submitted when delete or update are pressed...
I wrote a jsfiddle for you:
https://jsfiddle.net/yL35bh10/
I recently prototyped a page needing image file upload. I found a package on GitHub that was easy to use and should provide the majority of the functionality you're needing.
https://github.com/blueimp/jQuery-File-Upload
My only question to you: Once a file is uploaded to the server, how are you going to know what to delete?

Making form's onsubmit to work only for particular submits

In PHP program, I have JS function which validates submit <form ...onsubmit='return isOK();'>. It works OK. The problem is I want it to work only for particular submits, not for all. Is there any way inside the JS function to find out which submit was pressed, or some PHP trick
instead of onsubmit u can use onClick.
<input type="submit" onclick="return pressSubmit1()" value="submit1" />
<input type="submit" onclick="return pressSubmit2()" value="submit2" />
<form action="action.php" method="post">
...
<input name="submit" type="button" value="check me" onclick="submitform('check')" />
<input name="submit" type="button" value="do not check me" onclick="submitform('not check')"/>
</form>
in javascript:
function submitform(check)
{
if(check=='check') checkfrom();
}
in PHP
if($_POST['submit']=="check me")
checkform();
<form class="allowed" onsubmit='return isOK();'>
----
function isOK() {
if($(this).hasClass('allowed')) {
// Do stuff
}
}
your question is not clear, are you using a single submit button or different ones. If you're using different submit buttons then ofcourse you can make checks based on the id of the submit button. On the other hand if is a single submit button then it depends on what the conditions are for submitting or not submitting
It's better you write some HTML and Java Script code which you are using. So, it's easy to correct mistake is you have made somewhere in code snippet.
We can check which submit button is clicked, using PHP.
In the PHP page corresponding to the form submit, write
if(extract($_POST) && isset($submitbtn1)) {
// some validation for first submit button
}
elseif(extract($_POST) && isset($submitbtn2)) {
// some validation for second submit button
}
Note: we can use $ followed by submit button name inside the extract function. ie. $submitbtn1 is same as $_POST['submitbtn1']
Yes different onclick looks fine as mentioned in the accepted answer. But in the event handler you should have the
code as below. Note the preventDefault.
Also since submit is A button that submits the form. You can use button type instead of submit type and then there is no need for preventDefault. Here is the link of the code http://jsbin.com/wikose/4/
function testlogin(){
event.preventDefault();
var test = 'not validated';
if(test === "validated")
alert("not valid login");
else
$('form').submit();
return false;
}

Form in not sending the button data

I have a strange behaviour in my form, it sends the data from the textboxes but it doesn't send the button data.
This is my form:
<form name="login_registro" method="POST" id="login_registro">
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password">
<input type="submit" name="hacer_login" style="width:auto; height:auto; padding:5px;" class="button" onclick="submitForm('{{matches|last}}/entrar')" value="entrar">
<input type="submit" name="registro" style="width:auto; height:auto; padding:5px;" class="button" onclick="submitForm('{{matches|last}}/registro')" value="regístrate gratis!" >
</form>
The submit function:
<script type="text/javascript">
function submitForm(action) {
document.getElementById('login_registro').action = action;
document.getElementById('login_registro').submit();
}
</script>
In the two pages (entrar and registro) I did a print_R($_POST); and it only shows the two inputs, username and password. It doesn't shows the button pressed.
If I remove the onclick function, and add an action="page.php" it sends the two inputs plus the button pressed.
I know I can do a workaround, but I would like to know why this happend. Thanks.
PS: I commented all jquery.
Your problem here is that using onclick and submitting the form, will submit twice because the submit button already sends the form, and you add form.submit()
Use onsubmit="return submitForm('actionName')". If you return true at the end of the function, the form will get submitted. If you return false, the submission will be cancelled.
You can do this more elegantly by not setting the action dynamically and sending it as a field of the form, or parameter (set through the submitForm function), but this implies changes to your server-side code.
function submitForm(action) {
document.getElementById('login_registro').action = action;
}
I didn't understand at all your answer #Vicentiu Bacioiu, but you gave me a cue. How you said the form is submitted twice, so removing the line where it submit the form in the function worked for me.

How can i submit and redirect a form using jquery

I want to submit and redirect a form using jquery.I have tried to do it but redirect does not works, here is my code. The problem is i have two submit buttons in my form and both are redirecting to other page when i set the action=".....php".But i do not want update cart button to redirect to any other page so i want to use jquery for submitting and redirecting form. Please give me some solution. Thanks...
<script type="text/javascript">
$(document).ready(function(){
$('#updateCart').click(function(){
$('#form1').submit();
window.location.href='Checkout.php';
});
});
</script>
<form name="form1" method="post" id="cartform" class="clearfix" action="#">
<input type="submit" id="updateCart" value="Update Cart" class="btn-txt" name="update" onclick="update_cart()">
<input type="submit" class="checkout-button btn" name="checkout" />
</form>
You should do e.preventDefault(); on the update cart button and then fire the function that updates the cart.
Something like this:
<script type="text/javascript">
$(document).ready(function(){
$('#updateCart').click(function(e){
e.preventDefault();
updateCart();
});
});
</script>
You wouldn't want to fire the form submission when the "update cart" button is pressed, only when the "checkout" button is pressed.
Your approach is OK but you need to decide which button is your official form "submit" button, and which is attached to a jQuery function to update the form before submitting.
I would recommend that you don't do any javascript for your main "Checkout" button as you will want this to go to a payment page where you capture payment details - i.e. the form will follow it's action="checkout.php".
For your "Update Cart" button follow APAD1's answer and adapt it to your needs. If you're going to be updating form fields you'll need to think about using JSON-encoded returned data...
You could just make it an html button that doesn't submit by setting it's type to "button" and then it will just run the javascript when clicked. Then you can put the action attribute back on your form and it will only submit for the checkout submit button.
<button type="button" id="updateCart" class="btn-txt" name="update" onclick="update_cart()">Update Cart</button>
add id or class in form tag
<form id="form1" ...>
change submit button to anchor
<a id="submitAnchor"> ... </a>
and in javascript submit the form and redirect the user as well
$("#submitAnchor").click(function(){
$(".form1").submit();
setTimeout(function() {
window.location = 'your URL';
}, 1000);
});

Triggering onclick event of Input/Form

<form method="POST" onsubmit="return false;">
...
<input type="submit" name="button" value="Login" onclick="require('file.js').submitForm(this.form);">
...
</form>
How can i trigger onclick event of this INPUT element (so it can submit the form) in Internet Explorer 9 using javascript?
I tried:
document.getElementsByName("button")[0].click()
and
document.getElementsByName("button")[0].onclick()
but neither works.
(document.getElementsByName("button").length = 1)
you can use
document.getElementsByTagName("form").submit();
and for click event you can use this
element = document.getElementsByName("button")[0]
if (typeof element.onclick == "function") {
element.onclick.apply(element);
}
Looking beyond the surface of your question, I believe you're trying to trigger a form post AND handle the submission with some client-side logic.
The code you have prevents the form from being posted because of "return false;". When the button is clicked, it'll triggered the submit event, which is blocked. So how do you know that the button is triggered or not, knowing the results are the same?
For simpler coding logic, put the JavaScript call either in the form tag or the button but not both. My advice is to leave the button be. type="submit" means it will submit the form. The the form itself has a JavaScript function that decides whether to post or not.
<form method="POST" onsubmit="return prepost();">
...
<input type="submit" value="Submit">
</form>
<script>
function prepost(){
// if the form needs to be stopped
return false;
// if the form needs to be posted
return true;
}
</script>
Answer: The form didn't submit if I left some fields blank. When i put correct values in right fields it submitted correctly using above click() method. Thank you all for answers.

Categories