Here is a form
<cfoutput>
<form name = "xrefform"
id = "xrefform"
action = ""
method = "post"
onsubmit = "return submitx('#coltop#', '#col#')">
</cfoutput>
There are two different way to submit it:
1) when you want the data in the form to be placed in a MySql Table
2) when you want the data to be deleted from the Mysql Table
For the first case I have
<input type = "Submit"
name = "SubmitXref"
class = "submitbut"
value = "Submit"
onclick = "aasubmit('xref2.cfm')">
with corresponding javascript:
function aasubmit(target) {
document.xrefform.action = target;
}//end function aasubmit
This works fine.
For the delete case I have
<input type = "Submit"
id = "delbut"
class = "onoffbut"
value = "delete"
onclick = "aasubmit('repdel.cfm')">
This has a problem, which is that the submitx() javascript runs, and in this case I don't want it to.
I find references that say using the document.form.submit() method will avoid running the onsubmit function. But I can't figure out how to indicate the action.
Can someone show me how to do this?
After fussing around some more I found the answer:
For the delete button --which needs to evade the onsubmit script --here is the HTML:
<input type = "button"
id = "delbut"
value = "Delete this item"
onclick = "buttonsubmit('xrefdel.cfm', 'xrefform')">
And here is the javascript.
function buttonsubmit(target, source) {
var q = document.getElementById(source);
q.action = target;
q.submit();
}
This works perfectly. The ordinary submit honors the onsubmit script, the delete button skips it.
Let's outline your requirements:
One form
Two submit buttons
No JavaScript submit.
If you give each of the submit buttons a name, then you can have a single action page and check which button was clicked.
name="doUpdate" or name="doDelete"
The only name key that will exist in the form scope is whichever submit button was clicked. Use structKeyExists() to check and process accordingly.
Of course, you probably want to use onsubmit="return validateForm()" to call a validation function. If you click on "delete", you might want the user to confirm that was what they wanted to do before processing it. The function validateForm() just needs to return true or false, so you'll still avoid the JavaScript submit().
Do something like this in the form:
<input name="action" value="save" id="action" type="hidden">
<button type="submit" class="button button-basic-green" onclick="document.getElementById('action').value='save';"><span class="fa fa-save"></span> Save</button>
<button type="submit" class="button button-basic" onclick="document.getElementById('action').value='reload';"><span class="fa fa-repeat"></span> Save & Reload</button>
<button type="submit" class="button button-basic" onclick="document.location.href='./';return false;"><span class="fa fa-arrow-circle-o-left"></span> Cancel</button>
Note the default action of "save". Gets you something like:
Then in the singular form-action page, check to see what the form.action is and process accordingly.
<cfif form.action eq "reload">
<cfset loc="page.cfm?id=#form.id#">
<cfelse>
<cfset loc="./">
</cfif>
In my jsp, I have something like this
<%
String isMultipleOfficesExists = (String)request.getAttribute("MultipleOfficesExists");
String isMultipleOfficeSecurity = (String)request.getAttribute("MultipleOfficeSecurityExists");
String envParm = "default";
if("true".equals(isMultipleOfficesExists)){
envParm = "multipleOffice";
}else if("true".equals(isMultipleOfficeSecurity)){
envParm = "multipleOfficeSecurity";
}
%>
At the bottom of my form, in my submit button, I am calling a JavaScript On-click function.
<input class="white_button_extra_large" type="button" value="<%=goBtn%>" onclick="javascript:selectEnvironment(envParm);">
And my script section is :
function selectEnvironment(envParm)
{
resetToken();
logoutFlag = false;
document.forms[0].action = contextURL+'/login/selectEnvironment?envParam=' +envParm;
document.forms[0].submit();
}
But I am getting Uncaught ReferenceError: envParam is not defined
How can I solve this?
Make your envParm variable global in JSP. And your on click event should be like follows
<input class="white_button_extra_large" type="button" value="<%=goBtn%>" onclick="javascript:selectEnvironment('<%=envParm%>')">
You should pass the value from javascript function. The parameter should have value. Refer this linkPassing arguments
I'm trying to use a submit button to pass 2 parameters, userId and friendId, using jsp into the same servlet. I am able to obtain friendId, however, I am not able to obtain the userId.
function anotherPageServlet(servletName) {
document.forms[0].method = "post";
document.forms[0].action = servletName;
document.forms[0].submit();
}
function anotherPageServlet1(servletName) {
document.forms[0].method = "post";
document.forms[0].action = servletName;
document.forms[0].submit();
}
<input style="color:#3333ff"
type="submit"
class="rsubmit"
value="<%= retrieving.getDisplayname()%> :"
onclick="anotherPageServlet('ViewingFriendServlet?stringParameter=<%= session.getAttribute("userId") %>'),
anotherPageServlet1('ViewingFriendServlet?stringParameter=<%=retrieving.getoID() %>')"
>
You probably only need to escape the quotes:
onclick="anotherPageServlet('ViewingFriendServlet?stringParameter=<%= session.getAttribute(\"userId\") %>'),
anotherPageServlet1('ViewingFriendServlet?stringParameter=<%=retrieving.getoID() %>')"
I'm not used to JSP, but in JSF you would rather assign values to a request-scoped bean and then call a function that works with that bean, rather than passing those arguments directly.
EDIT:
Define onclick functions first, then call only the simple reference.
function servletFoo() {
anotherPageServlet('ViewingFriendServlet?stringParameter=<%= session.getAttribute("userId") %>');
anotherPageServlet1('ViewingFriendServlet?stringParameter=<%=retrieving.getoID() %>');
}
Then in your HTML:
<input ... onclick="servletFoo()" />
I'm learning JavaScript and am unable to make a button inside of a form that doesn't submit the form. There is a similar question here but the most popular answer to specify type="button" doesn't work in my case and other answers involve jQuery, which I would like to leave out for now.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function submit(){
alert("Yo")
}
</script>
</head>
<body>
<form name="myForm" onsubmit="submit()">
<input type="button" value="Submit!" onClick="submit()" />
</form>
</body>
</html>
Since you're not using a type="submit" the only reason your form would submit anything is because you're literally calling the submit() method when the button is clicked. (well, sort of. It's actually form.submit() - the method you created is window.submit()).
By default, an input of type="button" will not do a form submission unless you literally call form.submit()
Pass along the event as an argument in your submit function, and prevent its default behaviour:
function submit(event) {
event.preventDefault();
alert('Yo');
}
onClick='submit(event)'
Dating from the introduction of Javascript by Netscape Corporation, form element event handlers defined as HTML attribute values were provided with a special scope chain which searches properties of the element clicked and the form element ahead of searching the global object. [This was a convenience for web programmers and predated the introduction of a Document Object Model with standardized methods for access and manipulation.] Hence
<input type="button" value="Submit!" onClick="submit()" />
when clicked executes the anonomous function created from the HTML attribute string:
function( event) { submit()}
which searches its scope chain for submit and finds it as a property of the enclosing form object. Possible solutions include
explicitly specifying the global version of the function to execute:
onclick="window.submit()"
naming the global function something else, say "preSubmit", which does not conflict with the property of the form object:
onclick="preSubmit()"
adding the click event handler to the button in javascript after the button element has been created (only function specified in HTML have a special scope chain).
Section `19.1.6. Scope of Event Handlers" within chapter 19 of "Javascript the Definitive Guide" from O'Reilly is the only link that I have been able to find which discusses this.
updated after #progysm's comment on another answer
The scope chain of an HTML provided event handler is now covered in the HTML5 standard, under internal raw uncompiled handler, list item 1.10, which indicates the lexical scope of the handler includes the element clicked, the form it belongs to (if any) and the document object. I would caution against relying on this too heavily: some browsers used to include every parent object of a clicked element in its scope chain, not just its form and document.
To prevent your button from submitting, you can either:
Use preventDefault() on the onsubmit event of the <form> or
Use return false at the end of the operation on the onclick event of the button.
The code:
<html>
<head></head>
<body>
<form name = "myForm" method = "POST">
<input name = "button" type="submit" value="Submit!"/>
</form>
<script type = "application/javascript">
document.forms.myForm.onsubmit = function(e) {
e = e || event;
e.preventDefault();
}
document.forms.myForm.button.onclick = function () {
// Your code
return false; // Prevents the button from trying to submit
}
</script>
</body>
</html>
Notes:
Be sure to use the method attribute in the <form> tag as it's required.
e = e || event means that e will be equal to e in all the browsers that recognise it and equal to event in browsers that recognise event.
document.forms.[form name].[input name] is another way to get an element based on its name, in contrast to document.getElementById() which requires the id of the element, which have not set in your HTML.
You can test the code's functionality live with the following snippet:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head></head>
<body>
<!-- The form we don't want to submit -->
<form name = "myForm" method = "POST">
<input name = "button" type="submit" value="I will not submit!"/>
</form>
<!-- The form we want to submit -->
<form name = "myForm2" method = "POST">
<input name = "button2" type="submit" value="I will submit!"/>
</form>
<script type = "application/javascript">
// For the form we don't want to submit
document.forms.myForm.onsubmit = function(e) {
e = e || event;
e.preventDefault();
}
document.forms.myForm.button.onclick = function () {
console.log("NOT Submitted!");
return false;
}
// For the form we want to submit
document.forms.myForm2.button2.onclick = function () {
console.log("Submitted!");
}
</script>
</body>
</html>
function onFormSubmit()
{
console.log('FORM SUBMITTED');
return false;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<form name="myForm" onsubmit="return onFormSubmit()">
<input type="submit" value="Submit form! [input type = submit]" /><br />
<input type="button" value="Submit form! [input type = button, onclick = form.submit]" onClick="return onFormSubmit();" /><br />
<!-- in real test change onClick behavior
return onFormSubmit();
to:
form.submit();
Here I used onFormSubmit() because when you calling form.submit() browser doesn't dispatch onsubmit event -->
<button>Submit form! [button]</button><br />
Submit form! [a, onclick = form.submit]<br /><br />
<input type="button" value="Click me, no submit! [input type = button]" /><br />
</form>
</body>
</html>
If you wish to conditionally consume the event or not, simply return true or false from your handler function, like so...
JavaScript:
function validate() {
var valid = true;
// the following two validation functions would return a Boolean.
valid = valid && validateUsername();
valid = valid && validatePassword();
// If validation is fine, return true and this allows post to continue.
// If validation is not fine, return false and this disallows the submission from going ahead.
return valid;
}
HTML:
<form name="frmTest" id="frmTest"
method="post" action="example.action"
onsubmit="return validate();">
</form>
If you don't need it to be conditional, just return false, of course.
This solution works in native javascript. Doesn't prevent return key in inputs, it does what it should - stop a form from submitting on enter
function preventReturnKeyFormSubmit(){
//listen to key press events
window.addEventListener('keydown', function(e){
//set default value for variable that will hold the status of keypress
pressedEnter = false;
//if user pressed enter, set the variable to true
if(event.keyCode == 13)
pressedEnter = true;
//we want forms to disable submit for a tenth of a second only
setTimeout(function(){
pressedEnter = false;
},100)
})
//find all forms
var forms = document.getElementsByTagName('form')
//loop through forms
for(i = 0; i < forms.length; i++){
//listen to submit event
forms[i].addEventListener('submit', function(e){
//if user just pressed enter, stop the submit event
if(pressedEnter == true) {
e.preventDefault();
return false;
}
})
}
}
//run this function inside document onload/domready/ or if using jquery .ready()
preventReturnKeyFormSubmit()
Simply make it return the function, and return false
<script type="text/javascript">
function submit(){
alert("Yo");
return false;
}
</script>
</head>
<body>
<form name="myForm" onsubmit="submit()">
<input type="button" value="Submit!" onClick="return submit()" />
</form>
</body>
</html>
In my view, I'm using a function, submitForm(action) to submit the form on button click. This is one of many buttons that will use this function. The action parameter will indicate which controller method to use.
The function seems to generate the correct Action attribute (the path is correct in the console), but it is always directed to the Index method rather than the action parameter.
The button:
<input type="button" value="Save Only" id="save" onclick="submitForm('SaveOnly')" />
The function:
function submitForm(action) {
var $form = $("#myForm");
$form.action = ("/Area/MyController/" + action);
$form.submit();
}
You're not accessing the 'action' attribute of the form itself, but to the jQuery selector result, in order for your code to work, you need to access the DOM element from inside the selector with $form[0].
I recommend to stick to jQuery, you're already using it!. Below is a working code with jQuery selectors.
<form id="myForm"></form>
<input type="button" value="Save Only" id="save" data-action="saveOnly" />
<script>
$('#save').click(function(){
var action = $(this).data('action');
var $form = $("#myForm");
$form.attr('action', "www.google.com?q=" + action);
$form.attr('method', 'GET');
$form.submit();
});
</script>