Is there a better jQuery solution to this.form.submit();? - javascript

I want to trigger the submit event of the form the current element is in. A method I know works sometimes is:
this.form.submit();
I'm wondering if there is a better solution, possibly using jQuery, as I'm not 100% sure method works in every browser.
Edit:
The situation I have is, as follows:
<form method="get">
<p><label>Field Label
<select onchange="this.form.submit();">
<option value="blah">Blah</option>
....
</select></label>
</p>
</form>
I want to be able to submit the form on change of the <select>.
What I'm looking for is a solution that works on any field within any form without knowing the id or name on the form. $('form:first') and $('form') won't work because the form could be the third on the page. Also, I am using jQuery on the site already, so using a bit of jQuery is not a big deal.
So, is there a way to have jQuery retrieve the form the input/select/textarea is in?

I think what you are looking for is something like this:
$(field).closest("form").submit();
For example, to handle the onchange event, you would have this:
$(select your fields here).change(function() {
$(this).closest("form").submit();
});
If, for some reason you aren't using jQuery 1.3 or above, you can call parents instead of closest.

this.form.submit();
This is probably your best bet. Especially if you are not already using jQuery in your project, there is no need to add it (or any other JS library) just for this purpose.

I have found that using jQuery the best solution is
$(this.form).submit()
Using this statement jquery plugins (e.g. jquery form plugin) works correctly and jquery DOM traversing overhead is minimized.

Similar to Matthew's answer, I just found that you can do the following:
$(this).closest('form').submit();
Wrong: The problem with using the parent functionality is that the field needs to be immediately within the form to work (not inside tds, labels, etc).
I stand corrected: parents (with an s) also works. Thxs Paolo for pointing that out.

You can always JQuery-ize your form.submit, but it may just call the same thing:
$("form").submit(); // probably able to affect multiple forms (good or bad)
// or you can address it by ID
$("#yourFormId").submit();
You can also attach functions to the submit event, but that is a different concept.

Your question in somewhat confusing in that that you don't explain what you mean by "current element".
If you have multiple forms on a page with all kinds of input elements and a button of type "submit", then hitting "enter" upon filling any of it's fields will trigger submission of that form. You don't need any Javascript there.
But if you have multiple "submit" buttons on a form and no other inputs (e.g. "edit row" and/or "delete row" buttons in table), then the line you posted could be the way to do it.
Another way (no Javascript needed) could be to give different values to all your buttons (that are of type "submit"). Like this:
<form action="...">
<input type="hidden" name="rowId" value="...">
<button type="submit" name="myaction" value="edit">Edit</button>
<button type="submit" name="myaction" value="delete">Delete</button>
</form>
When you click a button only the form containing the button will be submitted, and only the value of the button you hit will be sent (along other input values).
Then on the server you just read the value of the variable "myaction" and decide what to do.

In JQuery you can call
$("form:first").trigger("submit")
Don't know if that is much better. I think form.submit(); is pretty universal.

<form method="get">
<p><label>Field Label
<select onchange="this.form.submit();">
<option value="blah">Blah</option>
....
</select>
</label>
</p>
**<!-- <input name="submit" type="submit" /> // name="submit_new_name" -->**
</form>
<!--
this.form.submit == this.form.elements['submit'];
-->

Related

submitting form using jquery

got a problem and cant find the solution.
I am writing a chat. When a new user opens my site (a new session) a div popes out and the user is asked to fill in his name.
The form works fine when I use an input submit. I want it to work without the submit button, I want it to work when i press a div.
here is my code
html:
<form name="form" id="form" action="index.html" method="post">
<span id="nspan">First name:</span> <input type="text" id="firstname" name="name">
<div name="enter" id="enter">Submit</div>
</form>
the jquery:
$(document).ready(function(){
$("#enter").click(function () {
$("#form").submit();
});
});
nevermind is correct - no problem with that code.
Here's the JSFiddle to prove it: http://jsfiddle.net/8Xk7z/
Maybe you problem is that the id "form" is to general a name, and you already used it for another form.
Another thing, why not use a button or a link? You can style it like you want. Be careful when you use thing for what they are not suppose to be used for, it my give unexpected side effects.
In your case, you may only be able to login to you chat using a mouse, that would exclude blind people. You would also not be able to use the tabulater to get to the login "button". And last, if you are blind and uses a screen reader your would actually not know that there is at login "button", as the reader would not recognize the div as something you can click.
I would recomend using the button-tag like this
<button id="enter">Submit</button>
Or the a-tag like this
<a href id="enter">Submit</a>
If you don't like the predefined styling of them you may always override the styling.
try to define jquery at top of the page
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
Then put your script at next.
still issue.
Please check your other function on same page works fine or not.

Access 'post' data using JavaScript or check which submit button was used to submit the form

Consider a simple form with 2 submit buttons
<form method="post">
<button type="submit" name="command" value="cancel">Cancel Order</button>
<button type="submit" name="command" value="proceed">Save Order</button>
</form>
Once submitted, the server will know which submit button was used to submit the form by checking the value for command. Great!
In this case, I am using the onsubmit event handler of the form to preprocess and send the form data via AJAX. Like this: <form method="post" onsubmit="return ajaxSubmit(this);">
I'm using this ajaxSubmit function as a general way to check through any supplied form's elements and send the data via Ajax instead. This works fine for determining the value of text fields, if checkboxes are "checked", which radio is selected in a group, etc. The only thing it seems to get wrong (because I'm not sure how to check this) is which submit button was used to submit the form. i.e There is nothing in myForm["command"] to tell which of the 2 command buttons was actually used.
Instead, is there a way to access the same 'post' data that the server receives with JavaScript before it is sent?
Otherwise, is this just a flaw I need to work around? What's the best way?
Edit:
Since all modern browsers will pass the name/value of the button used to submit the form (along with the other relevant parts like which option is selected from a group, checked checkbox name/values, etc.) can anyone explain why there is no way to access this data directly before it is sent to the server? Is there a reason why we shouldn't be able to?
Instead, is there a way to access the same 'post' data that the server receives with JavaScript before it is sent?
Not that exact data, no.
The usual way to know which submit button was pressed is (unfortunately) to attach click handlers to the buttons and have them set a variable (or the value of a hidden field), which you can then check in your submit event handler.
Since you're using old-style DOM0 event handler attributes, probably the hidden field fits better with what you're doing:
<form method="post">
<input type="hidden" name="submitclicked" value="">
<button type="submit" name="command" value="cancel" onclick="submitClick(this);">Cancel Order</button>
<button type="submit" name="command" value="proceed" onclick="submitClick(this);">Save Order</button>
</form>
...where submitClick looks like this:
function submitClick(button) {
button.form.submitclicked.value = button.value;
}
...but I do recommend looking into using DOM2-style event handlers instead, or at least attaching DOM0 handlers in code blocks, as you can avoid creating global functions, share data without creating global variables, etc.
Just to be clear, you don't have to specify an onclick attribute on every element, the only reason I did that above is because you were using DOM0 handlers.
The better way to handle it is with event bubbling. Since the click event bubbles up to the form from its descendant controls, including the submit buttons, you can hook the event on the form and then look to see if it occurred on a submit button and, if so, what that button's value is.
For instance, here with a DOM0 handler, attached dynamically to the form, which will alert the value of the submit button clicked:
var form = document.getElementById("theForm");
form.onclick = function(e) {
// Get the event
e = e || window.event;
// Did it originate in an input[type=submit]?
if (e.target.tagName === "INPUT" &&
e.target.type === "submit") {
// Yes
alert(e.target.value);
}
};
Live Example | Source
Or using DOM2 handlers on any modern browser (not IE8 or earlier, but it would be easy to add attachEvent for those, which does much the same thing addEventListener does [and predates it]):
document.getElementById("theForm").addEventListener("click", function(e) {
// Did it originate in an input[type=submit]?
if (e.target.tagName === "INPUT" &&
e.target.type === "submit") {
// Yes
alert(e.target.value);
}
}, false);
Live Example | Source
Or using a library to make it easier (here it's jQuery, but most of them have this feature, which is called event delegation):
$("#theForm").delegate("input[type=submit]", "click", function() {
alert(this.value);
return false;
});
Live Example | Source (I'm using delegate there because I like the clarity; with recent versions of jQuery, you could use the hyper-overloaded on, but it's less clear. If you choose to, note that the order of arguments is different.)
The point here being that it's not complicated, difficult, or particularly cumbersome.
Re your ending question of your edit:
...can anyone explain why there is no way to access this data directly before it is sent to the server?
Probably not, no. It's important to understand that a lot of this stuff just evolved. The submit button's value being sent with the form is an HTML thing, apparently when doing the DOM HTML forms module, it just didn't occur to anyone to say "Hey, we should have a property on the form that only exists during the form submission event that tells you what submitted the form." It probably should have occurred to someone, but apparently, it didn't.
Another solution is to use a radio button instead of a submit button (you will have to design the radio to look as a button, though).
After submitting, the value of the field should be the one that was clicked. You can fetch the selected option by using jQuery's $("[name=command]:selected]"), or $("#theForm").serialize()
<form method="post" onsubmit="return ajaxSubmit(this);" id="theForm">
<input type="radio" name="command" value="cancel" id="cancel" onClick="document.getElementById('theForm').submit();">
<label for="cancel">Cancel Order</label>
<input type="radio" name="command" value="proceed" id="proceed" onClick="document.getElementById('theForm').submit();">
<label for="proceed">Save Order</label>
</form>
I think you can work this around by DELETING the other button, the one that that was not clicked. After that, you can run jQuery's serialize(), or access the value of the button that is left by any other means.
The code would be:
<form method="post">
<button type="submit" id=cancel name="command" value="cancel" onclick="document.getElementByid('submit').remove();submitClick(this);">Cancel Order</button>
<button type="submit" id=submit name="command" value="proceed" onclick="document.getElementByid('cancel').remove();submitClick(this);">Save Order</button>
</form>
All reasonable, but if you're going to go as far as attaching click handlers on all your submit buttons, it makes less sense to go through the hoops of the submit capability to manage your submission details.
Just make it so that the click handlers trigger a form submit while passing sufficient contextual information into the mix. Wait, click handlers typically tell you the source of the click already (there's your contextual information), especially if using some jQuery-ish framework.
So instead of:
<form onsubmit="doSubmit()" ...>
<input type="submit" onclick="updateSourceTo('cancel');" ... />
<input type="submit" onclick="updateSourceTo('submit');" ... />
Use:
<form ...>
<input type="button" onclick="doSubmit('cancel');" ... />
<input type="button" onclick="doSubmit('submit');" ... />
Or, if you'll be detecting the source by looking at the click event target:
<form ...>
<input type="button" onclick="handleSubmitButtonClick();" ... />
<input type="button" onclick="handleSubmitButtonClick();" ... />
For the nitty-gritty details of handleSubmitButtonClick, I should mention form.submit() and things like jQuery's event.target.
I admit that keeping with the submit-onsubmit paradigm promotes a certain purism to form handling, but IMO you're already stepping into non-purist lands with the use of two submit buttons.

When I use input type="button" a function works well but when I use button it doesn`t

I call the same function with those two types of button. With the first it works perfectly but with button it works well at the first but in less than one second it looks like refresh the page.
<input type="button" id="bProv" value="filtrar" onclick="filtroP()"/>
<button id="bProv" onclick="filtroP()">filtrar</button>
The type of a <button> element defaults to submit, so it will run the JS and then immediately submit the form.
Use <button type="button" ... if you don't want form submission.
That said, hard coding a button (which does nothing without JS) goes against the principles of unobtrusive JavaScript (which are part of best practise programming for the WWW).

javascript code to prevent bots from submitting form

I need a javascript code to prevents bots from submitting forms.
But i need a client side code in javascript that work like CAPTCHA but don't call the server
thank you
Most straight forward and simple way will be to add or edit form data on the fly when the button is actually clicked:
<input type="hidden" name="SubmittedByHuman" value="NO" />
<input type="submit" value="Submit me" onclick="this.form.elements['SubmittedByHuman'] = 'YES';" />
Having this, on the server side check the value of form element called "SubmittedByHuman" - if it will be "NO" it means something bypassed the submit button - or as people mentioned correctly in comments, user did click but has disabled JavaScript.
do something like
<h1>Type the result in the input box : 1+1</h1>
<input id="sum" type="text"/>
and before submitting you check if the value in the input is 2 and then submit it.
To improve this type of code you could randomly create these 2 values in the h1 and save them into a var and before submiting check if input and sum are the same.
I doubt this is possible, as bots are sophisticated enough to bypass most things.
Remember, the bot isn't going to open the webpage in a browser and press submit. It'll probably scan the page for a <form>, make a list of all the <input> fields, and perform a POST request containing all the data for each one.
It won't run any javascript, or press any buttons. You'll have to make the check server-side.

Using Javascript to submit forms

EDIT: For some reason if I change the input into an , the submit code works fine. Ok, this works, I'll just style the a tag to look like an input tag in css.
I am using a jQuery function to submit a form when a certain button is pressed, however this seems to have no effect on the form.
My code is as follows:
HTML:
<form id="loginForm" action="" method="POST">
<input class="loginInput" type="hidden" name="action" value="login">
<input id="step1a" class="loginInput" type="text" name="username">
<input id="step2a" class="loginInput" type="password" name="password" style="display:none;">
<input id="step1b" class="loginSubmit" onclick="loginProceed();" type="button" name="submit" value="Proceed" title="Proceed" />
<input id="step2b" class="loginSubmit" onclick="submitlogin();" type="button" value="Validate" title="Validate" style="display:none;" />
</form>
Javascript:
function submitlogin()
{
$("#loginForm").submit();
}
function loginProceed()
{
$("#step1a").fadeOut("slow",function(){
$("#step2a").fadeIn("slow", function(){
$("#step2a").focus();
});
});
$("#step1b").fadeOut("slow",function(){
$("#step2b").fadeIn("slow");
});
$("#step1c").fadeOut("slow",function(){
$("#step2c").fadeIn("slow");
});
}
However, when I press the button, absolutely nothing occurs.
PS. This function may seem meaningless since I can just use a input type="submit" but I originally intended this to have some more functionality, I stripped the function to its bare bones for testing purposes.
Try to use another name for input with name="submit". Without this it works fine for me.
You need to specify one form.
$("#loginForm").submit();
EDIT: Additional information added to question. You appear to be calling the wrong function. The submit button that is not display:none calls loginProceed() not submitlogin().
Also, if the functions are defined within jQuery's ready() function, they will be out of scope unless you define them as global.
Live example: http://jsfiddle.net/eSeuH/
Updated example: http://jsfiddle.net/eSeuH/2/
If the code you noted in the comment runs before the DOM is loaded, it will not work. You need to ensure that it does not run until the DOM has loaded (or at least the element it references has loaded).
$(document).ready(function() {
$("#loginForm").submit(function() { alert("clicked"); });
});
Additionally, your action attribute in your form tag is empty. What do you expect to happen when the form is submitted?
Try look in to Firefox debug console. Maybe you have errors in javascripts???
Because even if action is empty, all works.
For some reason if I change the input into an , the submit code works fine. Ok, this works, I'll just style the a tag to look like an input tag in css.
There's no jquery 'submit' method (not for ajax, at least): http://api.jquery.com/category/ajax/
You probably want to invoke form's submit method:
$("#loginForm")[0].submit();
Remember, jquery selector always returns array.
edit
'submit' will actually bind handler to submit event, not submit form:
http://api.jquery.com/submit/

Categories

Resources