Using Javascript to submit forms - javascript

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/

Related

How can automatically click on an hidden submint input tag when the user click on another shown input tag?

I am absolutely new in JavaScript and I have the following problem.
For some reason in a web page I have 2 input tag having type=submit, these:
<input type="submit" onclick="return myTestFunction();" value="Submit" id="submitEventButton">
<input id="submitButton" type="submit" style="display:none" onclick="return validateForm();" value="Submit" name="action:projectCreationAction">
As you can see the second one is hidden by the use of style="display:none"
Clicking on the first one I can enter into the myTestFunction() JavaScript method (that actually simply perform an alert).
I need to do the following thing: when the user click on the first button (the one having id="submitEventButton") automatically the hidden second button have to be clicked.
How can I do it?
Thanks!
You could place the following inside your myTestFunction, after the alert:
$('#submitButton').trigger("click");
Below is snippet you can run to check this out:
function myTestFunction(){
alert('hi from submit');
$("#submitButton").trigger("click") ;
}
function validateForm(){
alert('hi from validate form');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" onclick="return myTestFunction();" value="Submit" id="submitEventButton">
<input id="submitButton" type="submit" style="display:none" onclick="return validateForm();" value="Submit" name="action:projectCreationAction">
Instead of simulating a click or even having a second hidden submit button at all, you can just call the function that the second button is hitting from the first function:
function myTestFunction() {
// code here with alert
validateForm();
}
function validateForm() {
// code here
}
functions calling other functions is better practice than buttons triggering other click events.
this way is also pure javascript (no jquery) since i dont think with the implementation of your input code you are currently using jquery.
Your question is not so clear about it, but it seems like you don't really need the second button at least for what you're describing.
What you can do to achieve what you're after is add a call to validateForm() in the body of myTestFunction.
If you do not want to change the function for some reason, you can also change the first button like so:
<input type="submit" onclick="myTestFunction();validateForm();" value="Submit" id="submitEventButton">
It ain't pretty, and note that i assume here that myTestFunction doesn't return something important otherwise you can't discard the return as i suggested here, but other than that it would probably do the trick.

More submit button disabling on click with Jquery, doesn't work

I got this code here:
It works fine as far as disabling and replacing the Submit button goes, but it will not submit the form. My form uses the 'get' method and submits data to another page.
<script type="text/JavaScript">
$('.button').click(function() {
$('.button').remove();
$('.holder').append("DONT DOUBLE CLICK ANYTHING IN A BROWSER");
$('.form').submit();
});
</script>
I have tried most things, including changing .form to the id of my form, still no joy, any ideas would be helpful.
HTML code
<form action="liftingConfirm.asp" method="get" id="frmArchiveConfirm">
<input name="con_id" type="hidden" id="con_id" value="<%=request.querystring("con_id")%>" />
<input name="sub_id" type="hidden" id="sub_id" value="1" />
<input name="liftingDate" type="hidden" id="liftingDate" value="<%=Session("currentUSDate")%>" />
<div class="holder"><input name="btnConfirm" type="submit" class="button" id="btnConfirm" value="Start New Lifting Gear Examination" /></div>
You're using the wrong selector, the .form is looking for a <form> with a class of form. Furthermore you should be using the on() syntax:
$('form').on('click', '.button', function() {
$('.holder').append("DONT DOUBLE CLICK ANYTHING IN A BROWSER");
$('#frmArchiveConfirm').submit();
$('.button').remove();
});
For your jQuery code to work you should include the frmArchiveConfirm to your jQuery code as below.
Replace $('.form').submit(); with $('#frmArchiveConfirm').submit();
else if you only having one form in the page just use $('form').submit();
When you come across bug like this don't forget to make use of the firebug or the browser development tools. You can easily figure out the bug and what's wrong in your code.

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.

How to prevent form on submit behavior in jquery?

I need to get an .click() event and prevent form from behaving as it was initially designed and make my own changes and submit. How is it possible?
EDIT: Form input actually has an onclick defined behavior. I need to redefine it somehow.
EDIT: Some code
<form action='link' method='get'>
<input type="image" name="name" id="id" class="class" onclick="this.form.action='some_link'" title="Title" value="" src="image.gif">
</form>
If you don't want it to submit the form, return false at the end of your click function. If you want to submit the form, use the form element and call the submit function on it:
$('#myFormID').submit();
$('#form').submit(function(e) {
// Some code
});
I think it's enough.
You could use something like this (haven't tested it but it should work)
form = $("#yourform");
button = $("#yoursubmit");
button.click(function(){
dosomething();
form.submit();
return false;});

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

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'];
-->

Categories

Resources