This may be too short and sweet, but this is all I have to ask. When I have two buttons in HTML, I use one button for form submission, and another to trigger a javascript event. However, what is happening is that both buttons perform form submits. I want to use the other button for submits without making it unusable by javascript. WHat are the possible methods I can do this?
To expand on what Saravanan Sachi and aladin8848 already said:
If you are using <input> for your buttons, type="submit" will always submit your form and type="button" will be a plain, non-form submitting button.
If though you are using <button></button> tags for your buttons (as I tend to do), they have a 'default' type of submit, so you have to explicitly set their type to button ex. <button type="button">Do JS click things</button> to prevent it from submitting your form.
Use
<input type="submit">
to submit the form and
<input type="button">
to call JavaScript method
Use
<input type='button' onclick='....'>
instead of what you are probably using
<input type='submit'>
you can do the next:
var buttonList = document.getElelmentsByTagName('button');
buttonList[2].addEventListener('click', function(event){
event.preventDefault();
this.removeEventListener("click", this, false);
//do something, like add your own event
});
you should be more specific getting the buttons, and i don't test the code, but the idea is that, remove events and default behaviour of the second button.
i hope this helps you.
Related
There is a PHP-generated HTML 4 transitional page that is used to edit data from a database of a single record. The user has two options: to store changes or delete the record. I use a form with controls (some of them are hidden):
<form method="post" action="object_mod.php"><!-- this is another file -->
<!-- inputs follow -->
As I want to process two actions ie. delete or save a record I put two submit buttons on the form, before </FORM> tag:
<input type="submit" id="btnSubmit" value="Save">
<input type="submit" id="btnDelete" value="Delete">
</form>
Because the user should confirm deletion I added the following onclick event:
<input type="submit" id="btnDelete" value="Delete" onclick="javascript:deleteRecordConfirm();">
(I also tried without javascript: and onclick="javascript:deleteRecordConfirm(); return true;"), but it doesn't submit a form.
The JS function is
function deleteRecordConfirm(){
if(confirm('Are you sure to delete?')){
document.getElementById("field_action").value=-1;
//document.forms[0].submit();
return true;
}
}
This field_action is set to -1 so I know in object_mod.php that I want to delete record rather than save it.
Here go question, why this form doesn't submit on deletion?
I think it would be good if a user has Javascript disabled to submit a form anyway, even without confirmation so that is why I use <INPUT TYPE="submit"> for deletion. Is it a good idea? I was thinking about giving two independent forms (in fact deletion should have only one hidden field with record id) with their own submit buttons, one for deletion and the other for saving.
In fact the page will work in some kind of intranet, with users who I trust and I'm not afraid of hacking or something, but any security remarks are also welcome.
(I tested it on Firefox 19.0 and Javascript console shows no errors, w3c validator says it's a valid page).
The form should submit according to your code. The only thing I spot is that you should terminate the input tags with />.
BUT... this way, even if the the confirm is cancelled, the form will be submitted. Use the form.onsubmit handler and if that returns false, the form will not submit.
I dont think #B3aT's answer is right in that not unconditionally the best way to "externalise" so to say. Many the the simplest is the best.
I think the best way is to "externalize" the actual form posting.
//make regular buttons (not submit)
//call your own functions (save and delete)
//after you have done your logic do document.forms["myform"].submit();
Another solution is to add a checkbox named "delete" and rename the "save" button to "Done or do". And on server side, if "delete" is activated, then ..delete it.
Usually the "delete" is required "per entry" level (same user have multiple records), so you will have to make a separate button/link and eventually do an ajax request/access an URL with ?delete=1&id=3.
You need to make custom yes/no windows or use a jQuery plugin for it, the only browser standard is "confirm".
OK, it worked, and this was in fact very stupid mistake. The problem was with this button as it was outside the form. I was so sure that I have it inside that I did not review PHP code but copied all from script not the HTML output as I should have done.
As I understand this correctly the line document.forms[0].submit(); worked but it was not because it was button who submitted the form but document.form[0] object itself.
Thank you for all your answers. I will try this form.onsubmit hint from Marcell.
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.
I'm making a web page using CGI scripting which has a form users need to fill out. The general layout is:
<form>
textfield (username)
textfield (password)
textfield (email)
submit button
</form>
What I would like to do is add a button that checks to see if the username they've entered is available. My problem is the way I'm trying to go about doing this is by writing:
<form>
<form>
textfield (username)
submit button
</form>
textfield (password)
textfield (email)
submit button
</form>
This doesn't work, the submit button instead submits the outer form. Here are the things I've considered trying but have not worked:
Put a form at the end of the first form. Problem: I have no idea how to align the "validate" button next to the username text field button without making it float which causes a bunch of other issues with the page.
Put values on the submit buttons and make the submit do different things based on which button was clicked. Problem: the web page that I want to make a "POST" request to is different based off which button is pressed. Seeing as I put the action="mypage.cgi" in the portion of the code, and not the button portion, I don't know how to make it go to different sites based on which button I press.
First of all it is a good idea to give all forms names.
So you can easily distinguish between forms.
Next, attach onClick even to each button that would call a function with a different paramenter: 1,2,3. Each button would send its own parameter. In the function you just look at the paramenter and submit appropraite form.
<form name='form1'>
....
<button type="button" onClick=doIt(1);>Submit</button>
</form>
<form name='form2'>
....
<button type="button" onClick=doIt(2);>Submit</button>
</form>
<form name='form3'>
....
<button type="button" onClick=doIt(3);>Submit</button>
</form>
<script>
function doIt(formid)
{
if(formid==1)
{
document.form1.submit();
}
if(formid==2)
{
document.form2.submit();
}
...
}
</script>
Have multiple submit buttons with different names. Check for each on the post back.
The approach that I have used for nested forms is to use tag instead of tag,
and then appending the form tags at the time of clicking submit buttons.
I have written a small JQ Plugin-'dynaForm' for the same, and its very easy to implement.
Please refer to ==> http://anupampdhyy.wordpress.com/2014/09/29/dynaform/
and
you can also watch a demo for same at :
https://www.youtube.com/watch?v=CFQia8EsoPQ&feature=youtu.be
I hope this helps you to implement nested forms in your HTML code. :)
You probably need to make two different form actions, so that you don't submit two completly different values.
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.
I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:
$('form').keypress( function( e ) {
var code = e.keyCode || e.which;
if( code === 13 ) {
e.preventDefault();
return false;
}
})
As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.
Does anyone know of a more sophisticated technique for doing this?
Similarly, are there any pitfalls to this solution that I'm just not aware of?
Thanks.
Using
<button type="button">Whatever</button>
should do the trick.
The reason is because a button inside a form has its type implicitly set to submit. As zzzzBoz says, the Spec says that the first button or input with type="submit" is what is triggered in this situation. If you specifically set type="button", then it's removed from consideration by the browser.
It is important to read the HTML specifications to truly understand what behavior is to be expected:
The HTML5 spec explicitly states what happens in implicit submissions:
A form element's default button is the first submit button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.
This was not made explicit in the HTML4 spec, however browsers have already been implementing what is described in the HTML5 spec (which is why it's included explicitly).
Edit to add:
The simplest answer I can think of is to put your submit button as the first [type="submit"] item in the form, add padding to the bottom of the form with css, and absolutely position the submit button at the bottom where you'd like it.
Where ever you use a <button> element by default it considers that button type="submit" so if you define the button type="button" then it won't consider that <button> as submit button.
I don't think you need javascript or CSS to fix this.
According to the html 5 spec for buttons a button with no type attribute is treated the same as a button with its type set to "submit", i.e. as a button for submitting its containing form. Setting the button's type to "button" should prevent the behaviour you're seeing.
I'm not sure about browser support for this, but the same behaviour was specified in the html 4.01 spec for buttons so I expect it's pretty good.
By pressing 'Enter' on focused <input type="text"> you trigger 'click' event on the first positioned element: <button> or <input type="submit">. If you press 'Enter' in <textarea>, you just make a new text line.
See the example here.
Your code prevents to make a new text line in <textarea>, so you have to catch key press only for <input type="text">.
But why do you need to press Enter in text field? If you want to submit form by pressing 'Enter', but the <button> must stay the first in the layout, just play with the markup: put the <input type="submit"> code before the <button> and use CSS to save the layout you need.
Catching 'Enter' and saving markup:
$('input[type="text"]').keypress(function (e) {
var code = e.keyCode || e.which;
if (code === 13) {
e.preventDefault();
// also submit by pressing Enter:
$("form").submit();
}
});
Pressing enter in a form's text field will, by default, submit the form. If you don't want it to work that way you have to capture the enter key press and consume it like you've done. There is no way around this. It will work this way even if there is no button present in the form.
You can use javascript to block form submission until the appropriate time. A very crude example:
<form onsubmit='return false;' id='frmNoEnterSubmit' action="index.html">
<input type='text' name='txtTest' />
<input type='button' value='Submit'
onclick='document.forms["frmNoEnterSubmit"].onsubmit=""; document.forms["frmNoEnterSubmit"].submit();' />
</form>
Pressing enter will still trigger the form to submit, but the javascript will keep it from actually submitting, until you actually press the button.
Dom example
<button onclick="anotherFoo()"> Add new row</button>
<input type="text" name="xxx" onclick="foo(event)">
javascript
function foo(event){
if(event.which == 13 || event.keyCode == 13) // for crossbrowser
{
event.preventDefault(); // this code prevents other buttons triggers use this
// do stuff
}
}
function anotherFoo(){
// stuffs.
}
if you don't use preventDefault(), other buttons will triggered.
I would do it like the following: In the handler for the onclick event of the button (not submit) check the event object's keycode. If it is "enter" I would return false.
My situation has two Submit buttons within the form element: Update and Delete. The Delete button deletes an image and the Update button updates the database with the text fields in the form.
Because the Delete button was first in the form, it was the default button on Enter key. Not what I wanted. The user would expect to be able to hit Enter after changing some text fields.
I found my answer to setting the default button here:
<form action="/action_page.php" method="get" id="form1">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
</form>
<button type="submit" form="form1" value="Submit">Submit</button>
Without using any script, I defined the form that each button belongs to using the <button> form="bla" attribute. I set the Delete button to a form that doesn't exist and set the Update button I wanted to trigger on the Enter key to the form that the user would be in when entering text.
This is the only thing that has worked for me so far.
You can do something like this.
bind your event into a common function and call the event either with keypress or button click.
for example.
function callME(event){
alert('Hi');
}
$('button').on("click",callME);
$('input ').keypress(function(event){
if (event.which == 13) {
callME(event);
}
});
I added a button of type "submit" as first element of the form and made it invisible (width:0;height:0;padding:0;margin:0;border-style:none;font-size:0;). Works like a refresh of the site, i.e. I don't do anything when the button is pressed except that the site is loaded again. For me works fine...
Is there a way to determine which element submitted a form from within an onsubmit handler? Trying to write a generic handler that knows which element was clicked. For example, given this form:
<form onsubmit="onSubmitHandler">
<input type="submit" name="submit1" />
<input type="submit" name="submit2" />
</form>
How can I determine inside the onSubmitHandler which submit button was clicked? I tried event.target/event.srcElement, but that gives the form, not the actual submit button.
Update: I'm writing a generic control here, so it has no idea what's on the form. The solution needs to work without knowing and changing the html of the form. My fallback is walking the DOM to find all buttons that could cause a submit, but I'd like to avoid that.
An alternative solution would be to move the event trigger from the form's submit event, to the submit element's onclick event, as such:
<form name='form1'>
<input type="submit" name="submit1" onclick="onSubmitHandler"/>
<input type="submit" name="submit2" onclick="onSubmitHandler"/>
</form>
In your handler function you can determine the submitting element simply by inspecting the event target's name, and if you need access to the form's information or other elements, you can get this from the submit elements "form" attribute.
I would not use a standard submit button-type.
Make the submit function take an extra argument which represents the element that submitted it, and the button would have an onclick that sends this as the parameter:
<input type="button" onclick="submitHandler(this)">
My fallback is walking the DOM to find all buttons that could cause a submit, but I'd like to avoid that.
...and adding click listeners to them to store the ‘last clicked’ button which is then read by the submit listener, right?
I can't think of any other way, sorry.
This solution works in Firefox. I haven't checked it in other compliant browsers or IE.
I'm not too hopeful for IE, you'd have to look into it and post your results.
<form id="myForm">
<input type="submit">
<input type="submit">
</form>
_
document.getElementById('myForm').addEventListener( 'submit', function( e ){
e.preventDefault();
e.explicitOriginalTarget.style.background = 'red';
}, false );
Click events bubble, so you could just add an "onclick" listener to the form itself, that checks if the click target source is a submit button; if so, store a reference to it somewhere associated with the form that you can access from your onsubmit handler.
If you want to handle "Enter"-submitted forms properly too, listen to the form's "onkeypress" or "onkeydown" event, check for "Enter", and clear your submit-button info if the event target ISN'T a submit button.