How to get function to fire when buttonless form is submitted - javascript

I have a page with many forms on it. could be 1..200. None of these forms have buttons and they are built programatically. I am using jquery to submit all the forms that are checked.
function FakeName()
{
$("input:checked").parent("form").submit();
}
My forms look like:
<form name="FakeForm<%=i%>" action="javascript:void%200" onSubmit="processRow(<%=i%>)" method="post" style="margin:0px;">
<input type="checkbox" name="FakeNameCheck" value="FakeNameCheck"/>
<input type="hidden" name="FakeNum" value="<%= FakeNum%>"/>
<input type="hidden" name="FakeId" value="<%=FakeIdr%>"/>
<input type="hidden" name="FakeAmt" value="<%=FakeAmount%>"/>
<input type="hidden" name="FakeTrans" value="FakeTrans"/>
</form>
Note: action is set to "javascript:void%200" so that it posts to a fake page. I want to handle my own posting in processRow.
OnSubmit never gets called and therefore ProcessRow never gets called.
Obviously all the names of the functions and variables have been changed to protect their identity :D
How can I get a function in each form to fire when I call submit programmatically.

The onsubmit handler is deliberately not triggered when you programatically submit the form. This is to avoid infinite recursion if an event handler would cause the event to be triggered again (and therefore the event handler to be called again)
However, of course you can call the processRow() function yourself in place of the .submit() call.
You're allowed to have inputs outside of forms. One school of thought is that a <form> shouldn't be a <form> if it's not intended to be submitted to the server via HTML.

Look up dispatchEvent and it's equivalent fireEvent. It's not the easiest thing in the world to use, but I think that's what you are looking for.
I'm surprised that there's no library that helps with this easily. Prototype (the one I've used the most) comes closest with a .fire() method on elements.

Looks like I may be able to do this:
<form name="FakeForm<%=i%>" action="javascript:processRow(<%=i%>)" method="post" style="margin:0px;">
<input type="checkbox" name="FakeNameCheck" value="FakeNameCheck"/>
<input type="hidden" name="FakeNum" value="<%= FakeNum%>"/>
<input type="hidden" name="FakeId" value="<%=FakeIdr%>"/>
<input type="hidden" name="FakeAmt" value="<%=FakeAmount%>"/>
<input type="hidden" name="FakeTrans" value="FakeTrans"/>
</form>
Are there any drawbacks to this?

Related

Submit form with Javascript then handle with PHP

Not sure how I did this last time or else I wouldnt asking here but here is what I'm trying to do.
I have the usual basic form with a javascript function that will submit the form. Question is that after the form is submitted, I have an if statement in PHP that echos a that the form has been submitted. Any help would be greatly appreciated.
//PHP
if($_POST['submitDelete']){
echo "welcome, You form has been submitted";
}
//HTML
<form id="form_id" action="" method="POST">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="hidden" name="submitDelete" TYPE="submit">
</form>
<button type="button" onclick="myFunction()">Submit</button>
//JAVASCRIPT
<script>
function myFunction() {
document.getElementById("form_id").submit();
}
</script>
I can't seem to trigger the if statement in PHP. I also tried using the form name in the if statement and that didnt work either.
A form element must be told where to submit its data to when the submit event takes place. This is accomplished by setting the action attribute value for the form. Leaving that attribute empty does not implicitly set the form to post back to the current page. So, if you want to have a single page form/form processor, you need the action to be set to the current page file name:
<form action="currentPageFileName.php" method="post">
Next, there's no reason a single page can't have multiple forms on it. In that case you would need multiple submit buttons, each tied to a specific form. For this reason, you can't just drop a submit button anywhere on the page that you like unless you add the form attribute to the button to tie it back to the form it is supposed to trigger the submit for. Also, if you simply place the submit button within the form element it "belongs" to, you don't have to worry about this.
Also, you have some invalid HTML with:
<input type="hidden" name="submitDelete" TYPE="submit">
An element may not have the same attribute repeated within it (the case that you type the attribute in makes no difference since HTML is not case-sensitive). So, that code would wind up simply creating a submit button.
Lastly, if all you want to do with your submit button is cause its related form to be submitted, there is no need for JavaScript at all. That is what submit buttons do by default.
So, in the end, you can get rid of the JavaScript in your code completely and change your HTML to this:
<form id="form_id" action="currentFileName.php" method="POST">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="hidden" name="submitDelete" value="true">
</form>
<button type="submit" form="form_id">Submit</button>

jQuery Trigger Reset Only Resetting Some Forms

I have many forms on my page that are DYNAMICALLY added and I have a button that I want to trigger a reset to all the forms on the page except one.
An example of a dynamically added form is:
<form>
<label for="code">Question code:</label>
<input type="text" id="code" name="code" maxlength="25" class="used"/>
<div class="clear"></div>
<label for="title">Question:</label>
<input type="text" name="titl" name="title" maxlength="255" class="used"/>
<div class="clear"></div>
<label for="hint">Hint:</label>
<input type="text"id="hint" name="hint" class="used"/>
<div class="clear"></div>
<input type="hidden" name="type" value="tapper" class="used">
<input type="hidden" name="optionsType" value="none" class="used">
<input type="reset" value="Cancel" class="delete-button">
<input type="button" value="Add" class="action-button" onclick="pushQuestion(this);">
</form>
Also, after each form is dynamically added, I call:
$('form').on('submit', function (e) {e.preventDefault()});
Now, when I want to reset the forms, I call the following:
$('form').trigger('reset');
When entering this into the console, I get an array back with all the DOM forms. Some forms get reset, but others are unaffected. There are no errors being reported. Does anyone have any thoughts as to why some get reset while others do not?
EDIT Thanks for the help, but the issue has been resolved. See the problem in the comments below
After a few hours of tinkering, it was discovered that the issue was the result of the way the forms were cloned.
I was doing a deep clone of the existing forms which was yielding an odd state of the form which means that when .trigger('reset') was "triggered", it would reset the form to the default state of the clone which may or may not have included some original data yielding a reset that did not appear to be doing anything.
A workaround was to first fire a loop over all the inputs with .attr(value,'') to clear the attribute value after cloning. Then the .trigger('reset') functioned as expected.
I've noticed some inconsistencies with form handling among the various browsers. One gotcha is that the less standards-compliant browsers require an input or button with type=submit for some things to function correctly. I know this is that case at least with submitting a form by pressing the enter key in any text field.
Maybe try adding an <input type='submit'/>?

Different Values in Form Inputs

I have a simple HTML form that works with a PHP script (to process the values).
For some reason it's not working correctly. After many tests, I inspect the mark-up for the form and I find:
<form id="delete_item_3_form" action="upload/delete_item.php" method="post">
<input type="hidden" value="4" name="item_id">
<input type="hidden" value="test" name="item_info">
</form>
As it should be. Please note that the values for the inputs are hard-coded.
However, if I go to the browser console (I am using Chrome) and write:
$('#delete_item_3_form');
I get:
<form id="delete_item_3_form" action="upload/delete_item.php" method="post">
<input type="hidden" value="4" name="item_id">
<input type="hidden" value name="item_info">
</form>
As you can see the value from the second input, item_info, is empty. Both inputs have a name.
I am not new to Form Handling but I have never seen this. The page mark-up shows one thing in a form, and a simple jQuery call to the same form shows another thing.
I have nothing, on my scripts, changing the value of the inputs.
The form is submitted by the press of a button. Here is the jQuery code:
$('#delete_item').click(function()
{
$("#delete_item_3_form").submit();
});
How is this happening?
I had another form in the page with the same ID.

Submitting a form with an INPUT outside it, and after modiying a value

I have a form, with a couple of <input> tags inside. I have a submit button (actually an <input> of type BUTTON, not SUBMIT) that is outside the form. I have the form set up similar to this —
<form name="testform" id="testform" action="test.jsp" onsubmit="return modify_value();" method="POST">
<input name="test1" id="test1" type="TEXT" value="A"/>
<input name="test2" id="test2" type="TEXT" value="B"/>
<input name="test3" id="test3" type="HIDDEN"/>
</form>
The submit button, which is outside the form, is defined this way —
<input type="BUTTON" id="_submit" onclick="document.forms[0].submit();"/>
And the modify_value() JavaScript method looks like this —
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'new_test_value_set_on_clicking';
return true;
}
When the submit button is clicked, I am trying to modify the value of the test3 element before the form gets submitted. For some reason, I can never read the new value in my servlet.
Alternate Method - (Doesn't Work Either) WORKS!
I have tried submitting the form in a slightly different way as well - by setting the button's onclick event to point to the modify_value() method and in the last line of that method, calling form.submit() instead of returning a value (EDIT: And of course, removing the onsubmit attribute in the form). This doesn't work either.
What am I doing wrong here?
When you call .submit() in JavaScript. The form's onsubmit event handler is not called.
I would put the button inside the form, and make it a submit button. Otherwise it's just a dead button (semantically, and when JavaScript is not available).
In HTML validation you're not allowed an INPUT element outside of a FORM element anyway. Weird, it seems you are! Ha ha I never knew that...
If you need to work within the restrictions specified within your answer, then remove the onsubmit attribute:
<form name="testform" id="testform" action="test.jsp" method="POST">
<input name="test1" id="test1" type="TEXT" value="A"/>
<input name="test2" id="test2" type="TEXT" value="B"/>
<input name="test3" id="test3" type="HIDDEN"/>
</form>
...and change the onclick attribute to modify the value...
<input type="BUTTON" id="_submit" onclick="modify_value()"/>
...and add the form submission to the end of the function, no need to return any value...
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'new_test_value_set_on_clicking';
document.forms[0].submit();
}
you can try this
<input type="BUTTON" id="_submit" onclick="modify_value()"/>
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'new_test_value_set_on_clicking';
document.getElementById("testform").Submit();
}
You can actually now do this entirely in HTML, see the form attribute for submit buttons all <input> elements — new with HTML5.
The form element that the input element is associated with (its form owner). The
value of the attribute must be an id of a <form> element in the same
document. If this attribute is not specified, this <input> element
must be a descendant of a <form> element. This attribute enables you
to place <input> elements anywhere within a document, not just as
descendants of their form elements.
Here's an example of how to use it:
<input type="submit" form="download" value="Download Selection" />
This button can then be placed anywhere on your page.
Obviously this only works on a limited number of browsers at the moment, but I figured it's worth a mention.
try this...
HTML
<form name="testform" id="testform" action="test.jsp" onsubmit="return false;" method="POST"> // onsubmit to return false
.....
<input type="submit" id="_submit" onclick="modify_value()"/> //call javascript function
</form>
JAVACRIPT
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'new_test_value_set_on_clicking'; // do the things here
document.getElementById('testform').Submit(); // submit the form
}

Javascript login form doesn't submit when user hits Enter

I'm working on a simple javascript login for a site, and have come up with this:
<form id="loginwindow">
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3,text4)
{
if (text1==text2 && text3==text4)
load('album.html');
else
{
load('failure.html');
}
}
function load(url)
{
location.href=url;
}
</script>
...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts?
Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.
There are several topics being discussed at once here. Let's try to clarify.
1. Your Immediate Concern:
(Why won't the input button work when ENTER is pressed?)
Use the submit button type.
<input type="submit".../>
..instead of
<input type="button".../>
Your problem doesn't really have anything to do with having used an onclick attribute. Instead, you're not getting the behavior you want because you've used the button input type, which simply doesn't behave the same way that submit buttons do.
In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons fire by default when ENTER is pressed from a focused element in the same form element. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit".
For example:
<form action="/post.php" method="post">
<!--
...
-->
<input type="submit" value="go"/>
</form>
2. Security concerns:
#Ady mentioned a security concern. There are a whole bucket of security concerns associated with doing a login in javascript. These are probably outside of the domain of this question, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).
Instead of drudging that up, here are links to related topics on SO, if anyone is interested in those questions directly.
Is there some way I can do a user validation client-side?
Encrypting Ajax calls for authentication in jQuery
3. Other Issues:
Here's a quick cleanup of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to illustrate some healthy habits. If you have specific questions about why I've written something a certain way, feel free to ask. Also, browse the stack for related topics (as your question may have already been discussed here).
The main thing to notice is the removal of the event attributes (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup.
<form action="#" method="post" id="loginwindow">
<h3>Login to view!</h3>
<label>User ID: <input type="text" id="userid"></label>
<label>Password: <input type="password" id="pass"></label>
<input type="submit" value="Check In" />
</form>
<script type="text/javascript">
window.onload = function () {
var loginForm = document.getElementById('loginwindow');
if ( loginwindow ) {
loginwindow.onsubmit = function () {
var userid = document.getElementById('userid');
var pass = document.getElementById('pass');
// Make sure javascript found the nodes:
if (!userid || !pass ) {
return false;
}
// Actually check values, however you'd like this to be done:
if (pass.value !== "secret") {
location.href = 'failure.html';
}
location.href = 'album.html';
return false;
};
}
};
</script>
Put the script directly in your html document. Change the onclick value with the function you want to use. The script in the html will tell the form to submit when the user hits enter or press the submit button.
<form id="Form-v2" action="#">
<input type="text" name="search_field" placeholder="Enter a movie" value=""
id="search_field" title="Enter a movie here" class="blink search-field" />
<input type="submit" onclick="" value="GO!" class="search-button" />
</form>
<script>
//submit the form
$( "#Form-v2" ).submit(function( event ) {
event.preventDefault();
});
</script>
Instead of <input type="button">, use <input type="submit">. You can put your validation code in your form onsubmit handler:
<form id="loginwindow" onsubmit="validate(...)">
it's because it's not a form submitting, so there's no event to be triggered when the user presses enter. An alternative to the above form submit options would be to add an event listener for the input form to detect if the user pressed enter.
<input type="password" name="text1" onkeypress="detectKey(event)">
Maybe you can try this:
<form id="loginwindow" onsubmit='validate(text2.value,"username",text1.value,"password")'>
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="submit" value="Check In"/>
</p>
</form>
As others have pointed out, there are other problems with your solution. But this should answer your question.
Surely this is too unsecure as everyone can crack it in a second ...
-- only pseudo-secure way to do js-logins are the like:
<form action="http://www.mySite.com/" method="post" onsubmit="this.action+=this.theName.value+this.thePassword.value;">
Name: <input type="text" name="theName"><br>
Password: <input type="password" name="thePassword"><br>
<input type="submit" value="Login now">
</form>
My Thought = Massive security hole. Anyone can view the username and password.
More relevant to your question: - You have two events happening.
User clicks button.
User presses enter.
The enter key submits the form, but does not click the button.
By placing your code in the onsubmit method of the form the code will run when the form is submitted. By changing the input type of the button to submit, the button will submit the form in the same way that the enter button does.
Your code will then run for both events.

Categories

Resources