JQuery: how to execute code before sending a form - javascript

I made a form and set its attr to onsubmit="return false"
Now I need to execute some actions before the actual submit like this:
$('input[name=submit]').click(function(){
$('.switch-input').attr('checked','checked');//getting all values of chbz
//here goes a little more code//
$('form[name=setform]').removeAttr('onsubmit');//finally sending to $_POST
});
At first glance everything works correct, but I wonder will it 100% execute all code before sending or did I do it wrong?

The onsubmit="return false" attribute will prevent the form from being submitted as it normally would be. However, when the user clicks the Submit input, the above snippet will execute once, removing the onsubmit attribute and making the form able to be submitted normally, but the user will have to click Submit again to submit it.
You can keep the existing snippet and tell jQuery to submit the form explicitly, via the third variation of the .submit() method:
$('input[name=submit]').click(function(){
$('.switch-input').attr('checked','checked');//getting all values of chbz
//here goes a little more code//
$('form[name=setform]').removeAttr('onsubmit');//make the form submittable
$('form[name=setform]').submit();//finally sending to $_POST
});
Alternatively, you can remove the onsubmit="return false" attribute, and use the .submit(handler) variation of the method, which simplifies your code and guarantees the handler will execute just before the form is submitted:
$('form[name=setform]').submit(function(){
$('.switch-input').attr('checked','checked');//getting all values of chbz
//here goes a little more code//
});

You could consider dismissing the onsubmit attribute and instead use your .click() code and just put return false at the end. You could also use .submit() as suggested by Stiliyan.

Related

How does preventDefault and type submit work with forms?

So I tried a couple of things when I using JS and try submitting inputs, and there are odd things I didn't understand the logic.
There is a difference between <input tpye="submit/> inside and outside of <form> tag. If it's inside the form tag I need to use preventDefault() function, but if it's outside form tag I am not required to do that if write simple js vanilla code.
Why is that?
What the difference between onsubmit and onclick ? especially in a form tag. Because If I use onsubmit the js code doesn't really work.
If I use preventDefault(event) it's preventing from the form to be sended into a server, and instead it doing the calculations with the browser only ?
Thanks !
By default, if you have an input of type "submit" in a form then clicking that input (or hitting enter after filling in ANY inputs in the form) will send a post or get request to the server, redirecting the current page to the server's response.
This was the original way to submit form data to a server, without using javascript. If you want to prevent this from happening, you can either replace the submit input with a plain button (<button onclick="doSomething()">Submit</button>), or prevent the default submission event: (form.onsubmit = event => event.preventDefault()).
The difference between onsubmit and onclick is that onsubmit only fires when a submission event is emitted from the form. To emit a submit event, the form needs an <input type="submit"> to be clicked, or for the user to trigger a submission by hitting enter.
Another way to prevent this default behavior is to return false in the submission handler.
onclick only gets fired when an element is clicked. Because events in javascript propagate up to parents, this will also trigger any onclick handlers on all parent elements.
If you want to completely ignore the default form submission behavior, then you can define a button with an onclick handler to handle your custom submission logic.
If you have a type="submit" input (Note, The default value for the type attribute of button elements is "submit") inside a form, the default action on click is to submit that form. To prevent it from submitting, place the button outside the </form>. This works because the button doesn't refer to any form to submit. You can instead, add a listener and call event.preventDefault(). This works because you are telling the browser NOT to take the default action (submitting the form)
onsubmit is used mostly on <form> elements. It triggers right before the form is submitted regardless of how it is submitted. onclick can be emitted from just about any element. It occurs when you click on an element. This could be on an <input>, a <button>. or even an entire <form>
Don't use this.

Will form submit twice if there's an onclick submit?

I've been told you need to add a "return false;" to the end of a method that submits the form.
I've tried the following code, and it appears though I omit the "return false" the form gets submitted only once, not twice. Does anyone know the standard browser behavior that dictates whether the javascript form submission overrides the html form submission or are they considered one action?
<form name="myform" action="">
<button type='submit' onclick='submitForm();'>Submit</button>
</form>
<script>
function submitForm(){
console.log('Button Clicked');
document.myform.submit();
}
</script>
if I change the button to be an input type, I also get only one submission not two, from my tests, but I want to confirm this is the standard behavior.
i.e.:
<input type='submit' onclick='submitForm();'/>
As stated in the comments of the answer you linked, the fact is that submit will only submit the data in the form you handled, while the onclick attribute will trigger your method call, which triggers inside it another submit.
I think it acts as follow (feel free to correct me if I am wrong):
You click on your button.
Clicking triggered the onclick value, which will call your submitForm() method.
Your method prints 'Button Clicked' in the console.
Your document is sent a first time.
Form is submitted a second time through its submit type.
That would explain why you see your console.log a single time. You would have to trace the result in your server-side in order to check if the document has been submitted once or twice.
(And if it is once, this answer is utterly wrong.)

Submit GET form in the url instead in the paramaters

I have a get method form which goes to
mysite.com/?p=search&q=QUERY
but I want to let the form send me to
mysite.com/search/QUERY.
I have rewritten URL turned on in .htaccess.
Any help? How do I do this?
Just remove the names of all these elements inside the form and take the values with js or jquery and set them to action attribute like
$('#formid).attr('action','/url/search/'+query);
You would do this in onsubmit event and return true so that form gets submitted.

HTML button to submit a form elsewhere on the page

I want to have a form on the main section of my webpage with buttons along the bottom of this section to submit it.
I also want to have a side bar with links to other pages, but make it so that whenever a link is clicked it acts as a button to submit the form too. (ie in the HTML, the code for these links will be outside of the form tags, but I would like them to still act as buttons for the form)
Is this possible?
You can solve this very easy without JavaScript in HTML5:
<input type="submit" form="id_of_the_form" value="Submit">
<form id="id_of_the_form" action method></form>
And you can style those buttons as you like. As in the example, the button can be placed at any point within the dom - no need to put it into the form.
Use the following onclick handler in your link, replacing formId with the ID for the form you want to submit...
onclick="document.getElementById('formId').submit();return false;"
Update
As #Juan (and others, especially #JoeTaylor) have mentioned, the above will not fire any client-side validation code associated with the form. The easiest way that I'm aware of to make it do so is to fire the click event of a submit button within the form. For instance, this could be used on your link...
onclick="document.getElementById('formSubmitButton').click();return false;"
Although you don't mention anything to do with server-side processing, I will take the assumption that is the point of your form. One additional thing I would say on the back of this is that you should ALWAYS replicate the validation back on the server. JavaScript is very easy to bypass, and so you should make sure the values reaching your server are correct, and never assume the JavaScript has done it's job.
The easiest way to ensure your form is submitted and validated by whatever function you've attached is not to call the form's submit() method, but to call its submit button's click() method instead.
Consider the following form:
<form id="bar" method="post" action="/echo/html/">
<input type="text" id="foo" name="foo">
<input type="submit" value="Submit">
</form>
Right now, clicking submit doesn't do anything special. But what if you wanted to ensure the text input had a value before sending anything off to the server? You might accomplish that as follows:
function validateBarForm() {
var txt = this.querySelector("input[type=text]");
if (txt.value == "") {
txt.style.outline = "solid red 2px";
return false;
}
}
document.getElementById("bar").onsubmit = validateBarForm;
Now if you click submit the form won't be submitted with a blank text input. But what if you submit the form programmatically? Let's add a link first...
submit form
Note that this link is outside of the form tag. We can trivially attach a submission function:
function submitBarForm() {
document.getElementById("bar").submit();
}
document.getElementById("submit-bar").onclick = submitBarForm;
We click "submit form" and... Whoops! The validation function is not performed! There are a few ways to skirt this issue, but my favourite is to simply have JavaScript simulate a click to the submit button. I find this holds up to changes a lot better than hardcoding a call to the validation function.
function submitBarForm() {
document.querySelector("#bar input[type=submit]").click();
}
Now when you click the link, the form is validated, and if everything checks out it's submitted too. But don't take my word for it--head on over to jsfiddle.net and see for yourself.
By adding an onclick javascript function to your form.
document.forms["myform"].submit();
Where "myform" is the id of your form. Here's a nice walkthrough: http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml
For example, the button might be:
<button onclick="document.forms['myform'].submit();">Hi</button>
Yes the button's click event add document.getElementById('formId').submit();
<form name="myform" action="action.php">
// Your form
</form>
Submit form
Or you can use jQuery:
<form name="myform" action="action.php">
// Your form
</form>
Your text
I do this myself with hidden submit buttons in the actual form, and outside of the form - anywhere else on the page - labels that reference the submit button and fire it.
In the form:
<input type='submit' id='hiddenSubmit'>
And anywhere else:
<label for='hiddenSubmit'>click me!</label>
Seems to do the job.

<html: image directly calling struts action class

I want to call submitformFinal(this.form); which is a client side validation.But the problem is that html:image property directly calls struts, so the server side validation takes place before calling the submitformFinal(this.form).
If submitformFinal fails , server side validations should not take place ,but in this case html:image directly calls the struts action classs.... any suggestions?
Right now my code is:-<html:image
src='<%=contextPath + "/img/save_orange.gif"%>'
onclick="javascript:submitformFinal(this.form); "/>
What about returning the value from submitformFinal():
<html:image src='<%=contextPath + "/img/save_orange.gif"%>'
onclick="return submitformFinal(this.form);"/>
Now if submitformFinal() returns false it wont submit, if it returns true then it will be submitted.
Update :
After seeing your next problem, here is my thoughts.
1) You should not use <html:image> for submitting the form. <html:submit> is the correct submit button tag. I will recommend to change the <html:image> to <html:submit>. U can add the image to the button by styleId, styleClass attributes. No need to call onClick on the button. It will just submit your form when you click it.
2) Now add onSubmit on the <html:form> tag like this:
<html:form action="someAction.do" onSubmit="return submitformFinal();">
This will work like as desired I guess.

Categories