Attach Event Handler to Node Syntax - javascript

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.

Related

EventListeners - Javascript [duplicate]

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

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.

Click event on button is trigged when submitting a form with enter

I have a form with two buttons, one input[type=submit] and one plain button which is the cancel button.
I have two event handlers, one bound to the form on submit and one bound to the button on click.
When I submit the form by pressing enter in an input the click event on the button fires (and before the submit event I might add), why is this?
This happens in both gecko and webkit.
Here's a working example:
http://jsfiddle.net/q3JPR/
If you submit by pressing enter I want the submit event to trigger, not the click event.
If you change your button to be <input type="button"... then your events will behave properly... here is the fiddle:
Working Fiddle
I also found this solution. If you set the type attribute to "button" <button type="button">My Button</button> it won't submit. I think not specifying the type by default sets it to submit. So you don't have to change the element to input.
Source: Add regular button inside form that does not perform a submit

html-javascript: page refreshes whenever an event is fired

I have an html page with buttons and such, to which I assign event listeners. Whenever one of the buttons is clicked, the page goes back to its original state, as if the browser had been closed and opened again. So if I have text fields into which I've inputted some info, they will be cleared as soon as a button is clicked, even if its event listener does nothing.
Likewise, if I include this event listener into the html, <body onload="pageLoaded();">, the pageLoaded() function will be called whenever a button is clicked.
Why is this happening, and how can I prevent it from happening?
Presumably you are using submit buttons, which will submit the form they are in unless you cancel the default action.
eventObject.preventDefault();
See the documentation.
Maybe your click event listener was added to a link or a button within a form. If so, you may add return false a the end of the listener to prevent the default behaviour being executed.
var link = $("#mybutton");
link.click(function() {
alert("clicked");
return false;
});
Setting the button type to "button" will resolve this issue. The default type is "submit" which as the others have said will submit the form.
<button type="button">Button</button>

Can I determine what button was clicked to fire an onSubmit event?

I've got an onsubmit handler added to a form like so:
$('#content_form').bind('submit',function(e) {
source = $(e.target).attr('name');
alert(source);
return false;
});
so e.target = the form element. I'm using several submit buttons, and need to determine which one was actually clicked (in modern browsers, that clicked button is the only one that submits, I'm doing this for IE6 compat - it submits the values of all the buttons).
My only thought it to kill any onsubmit events, and then tie click events to the buttons themselves. This would kill the form functionality entirely if javascript wasn't enabled, so I'd like to avoid this.
An easy (but possibly naive) implementation would be to have the onclick handler for each button set a field indicating which one was the last one clicked. In your submit handler, you could then check the value of this field.
$('#content_form input:submit').bind('click', function(e) {
$('#content_form').submit();
// you can now reference this or $(this),
// which should contain a reference to your button
});
Have you checked out the jQuery Form Plugin? It handles submitting forms via ajax very nicely and will handle this problem (along with many others) for you.
Something else you could do is use preventDefault(); instead of return false

Categories

Resources