EventListeners - Javascript [duplicate] - javascript

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...

Related

What button event should I use to confirm a html form?

Using Javascript, no framework, what button event should I use to confirm form when I wish not redirect? I expect to use either left mouse button or keyboard to confirm the form.
I used this element:
<button type="button" value="1">Save</button>
Using type="submit" with "submit" event is no solution for me because this creates redirection (values the from are lost). So I use type "button".
When I use
document.getElementById("advanced_form").addEventListener("click", saveOptions);
This even "click" is used with mouse. But there is possibility that the user will use keyboard instead mouse to submit form. So I suspect the form would not react to keyboard confirm action. I did not find any event related to button being pressed. So how to solve this problem?
You could still use ´type="submit"´ in combination with ´e.preventDefault();´ to aviod the redirect.
I hope this helped, good luck.
From your clarifying comment:
What happened is when I clicked the button the values which were in the form disapeared and so I understood it that the form was reloaded without any values.
Submitting a form...submits the form. What you get back as a result depends entirely on what the server sends back.
But the values should not disappear, the behaviour which I need is like in a normal Browser Window (WINAPI)
That is normal.
...the page will not clear the values. If I'd want to close the form, I'd close the tab (html page).
That isn't normal. Normal is for the form to go away and be replaced by the result of submitting it.
But you can do that with the submit event, just use event.preventDefault() within the submit event to prevent the form submission:
document.getElementById("the-form").addEventListener("submit", function(event) {
event.preventDefault(); // Prevents the form from being submitted
});
That event will reliably fire whether the user used the mouse, keyboard, or assistive technology to submit the form. The click event on a submit button will not reliably fire when the form is submitted with the keyboard or assistive technology.
You can use submit button, but you need to handle submit action. Try this (with jquery):
<input class="submit_button" type="submit" value="Save" />
<script>
function submit_form(e)
{
if (check_form_submit()) {
// check your data here
$(this).submit();
return;
}
e.preventDefault();
}
$(function() {
$('.submit_button').parents('form').submit(submit_form);
});
</script>
You should still use the submit input type but you need to prevent the default action so that the page doesn't reload.
If you are using jQuery this snippet should help.
$('#my-form').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
// Your code here
this.submit(); // If you want to submit at the end
});

Clicking submit button using javascript and Firefox

I guess I have never tried to do this before ... I have a button on a page.
<input type="submit" id="btn" value="Submit">
And a javascript function that includes:
function clickit()
{
alert(document.getElementById('btn').value);
document.getElementById('btn').click();
}
Using Firefox, the button is not clicked - i.e. the form is not submitted. The alert shows, but the form does not get submitted. Why won't Firefox click a button?
Use a div or anything besides a INPUT element if you want to bind the click event to it. If <INPUT> is inside a form body, you might run into weird issues.
If you just need to submit a form with a button I would recommend that you just use a <div> element with a click handler rather than an input. It will give you a little more flexibility. If you do that then you should be able to just select your form and use the submit() API to submit the form.
If you really can't modify the code enough to do this and are having trouble selecting and submitting here is how you will need to do that using both jQuery and DOM.
The jQuery Way:
$("my selector").trigger("click")
You may run into issues around focus if you're running in PhantomJS or you've got a window like a test runner that is not in focus. In this case you can use:
$(<my selector>).triggerHandler(<my event>)
The DOM API way
This will just trigger the event (the equivalent of the first example)
// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });
// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
You can also simulate a click with the actual DOM method
var button = document.getElementById('my-button');
button.click();
Why won't Firefox click a button?
I seem to recall that early versions of Firefox didn't allow calling of listeners that way for security reasons. However, I think those reasons have been addressed in other ways and now you should be able to call the click handler directly. The following submits the form in Firefox 34:
<form onsubmit="alert('submitted!!')">
<input name="foo" value="foo">
<input type="submit" id="aa">
</form>
<br>
<button onclick="document.getElementById('aa').click();">Click the submit button</button>
The form's submit listener is called and the form is submitted, so calling the submit button's click method is doing what it's supposed to.
This method doesn't work for all listeners though, click is a special case, see W3C DOM Level 3 Events Specification, §3.5 Activation triggers and behavior.

Attach Event Handler to Node Syntax

I've attached a 'click' event to a 'button' element (type=submit) so that clicking on the latter element copies data from one field (input type=text) to another. However, the copy is only temporary and reverts to blank or default values.
Affecting Firefox/Opera/Chrome
When the submit button is clicked, it also submits the form, which causes a page refresh.
You'll have to return false from your click event handler:
$('#theSubmitButton').click(function(){
// code to copy values goes here
return false;
});
Change the button input to type="button" instead of type="submit" if the button doesn't need to submit anything to the server (which by the looks of your question, it doesn't).
type="submit" will run the form's action/postback and cause a refresh.

How to assign 'return' as shortcut for anchor

Is it possible to assign the return key as a shortcut for an anchor. Just like when submitting a form if one of the input fields are on focus.
I have looked a little at the jQuery hotkeys but since I'm lacking some skills in js I can't quite figure it out.
My plan is that when the page loads the user can just press enter. Then an action will be performed followed by a redirect. I'm trying to do this
Reason for doing this is that I believe it's a lot faster for the user to press enter than to move the cursor and click on the link before the actual action takes place.
Much more simple will be to auto focus the link:
window.onload = function() {
document.getElementById("changeStatusLink").focus();
}
No jQuery is required and as it's focused, Enter press will trigger the click event.
If it's a form (e.g. with id #myform) why not to try to trap the user submit using this code. You need to put a hidden form submit element inside the form.
HTML
<form id="myform">
<input type="text" name="email" />
<input type="submit" style="display: hidden;" />
Click here to do some action
</form>
Javascript
$(function(){
$('#myform').submit(function(){
$(this); // this refers to the form
$('#your-link-id').click();
return false;
});
});
See: Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.
Note: the code is untested but it should work.

form with no action and where enter does not reload page

I am looking for the neatest way to create an HTML form which does not have a submit button. That itself is easy enough, but I also need to stop the form from reloading itself when submission-like things are done (for example, hitting Enter in a text field).
You'll want to include action="javascript:void(0);" to your form to prevent page reloads and maintain HTML standard.
Add an onsubmit handler to the form (either via plain js or jquery $().submit(fn)), and return false unless your specific conditions are met.
Unless you don't want the form to submit, ever - in which case, why not just leave out the 'action' attribute on the form element?
Simply add this event to your text field. It will prevent a submission on pressing Enter, and you're free to add a submit button or call form.submit() as required:
onKeyPress="if (event.which == 13) return false;"
For example:
<input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>
an idea:
<form method="POST" action="javascript:void(0);" onSubmit="CheckPassword()">
<input id="pwset" type="text" size="20" name='pwuser'><br><br>
<button type="button" onclick="CheckPassword()">Next</button>
</form>
and
<script type="text/javascript">
$("#pwset").focus();
function CheckPassword()
{
inputtxt = $("#pwset").val();
//and now your code
$("#div1").load("next.php #div2");
return false;
}
</script>
When you press enter in a form the natural behaviour of form is to being submited, to stop this behaviour which is not natural, you have to prevent it from submiting( default behaviour), with jquery:
$("#yourFormId").on("submit",function(event){event.preventDefault()})
Two way to solve :
form's action value is "javascript:void(0);".
add keypress event listener for the form to prevent submitting.
The first response is the best solution:
Add an onsubmit handler to the form (either via plain js or jquery
$().submit(fn)), and return false unless your specific conditions are
met.
More specific with jquery:
$('#your-form-id').submit(function(){return false;});
Unless you don't want the form to submit, ever - in which case, why
not just leave out the 'action' attribute on the form element?
Writing Chrome extensions is an example of where you might have a form for user input, but you don't want it to submit. If you use action="javascript:void(0);", the code will probably work but you will end up with this problem where you get an error about running inline Javascript.
If you leave out the action completely, the form will reload which is also undesired in some cases when writing a Chrome extension. Or if you had a webpage with some sort of an embedded calculator, where the user would provide some input and click "Calculate" or something like that.
Try preventDefault() method inside event listener for submit in this form

Categories

Resources