Detecting where a submit event came from with jQuery - javascript

I need to detect how a user submitted a form to generate some statistics. They can either press enter when typing on the input or they could click the submit button.
I tried binding a click event to the button and a keyup event to the input but what happens is when I press enter the click event is triggered. I read in some other thread that this is part of the new HTML5 spec or something like that.
I then thought of binding a submit event to the form and detecting there what originated that event, but I've had no luck so far. Is that even possible?
EDIT
I guess I managed to fix it. I changed my keyup event to keypress, like suggested by fortegente, and prevented the defaultEvents from firing while at the same time triggering a submit event on the form. That seemed to do the trick.

You can try add custom attribute. Something like this:
$('form').submit(function(){
alert($(this).attr('event'));
});
$("button").on('click', function() {
$("form").prop("event", "click").submit();
});
$("input").on('keypress', function() {
if (e.which == 13) {
$("form").prop("event", "keypress").submit();
}
});

Related

Prevent ng-click expression from firing on enter keydown

I have a simple button like this:
<button type="button" ng-click="$ctrl.method($event)">Test</button>
Here's what the ng-click expression looks like:
vm.method = function($event) {
console.log($event.type, $event.which);
};
When this button has focus (by way of navigating to it via the tab key) and I press enter, I get this output to the console:
click 1
To be more clear that's $event.type == 'click' and $event.which == 1.
I'm not sure why the ng-click directive allows the enter key to fire the assigned expression. Angular is recording enter keydown events as clicks. Is there a way to prevent this and have ng-click only handle click events (and ignore enter)?
This trivial bit of code is just an example, in my app I would like to use both ng-keydown and ng-click on the same component, but this particular issue is preventing me from fully implementing the functionality I want. Ideally, I'd like to have ng-keydown only handle keydown events, and ng-click only handle click events.
Possible but not best way is to check screenX/screenY/pageX/pageY/offsetX... props of $event. In case of "enter" they are equal to zero.
Just prevent default on the key press e.g.
vm.method = function($event) {
if($event.keyCode === 13){ //I think
$event.preventDefault();
}
console.log($event.type, $event.which);
};
If your button is inside a form and it's the only button, the click event will be fired on enter when the form has focus, depending upon the browser. You should be able to check the event object in your handler method and return false if it's the enter key triggering.
https://docs.angularjs.org/guide/expression#-event-

JQuery UI click event fires twice on keypress

HTML
<button id="clickMe" tabindex=0>Click Me!</button>
JS
$('#clickMe').button();
$('#clickMe').click(function() {
alert('hey');
});
$(document).keypress(function (e) {
var key = e.keyCode ? e.keyCode : e.which;
//detect when the user has hit enter
if (key == 13) {
//click the focused element
$(document.activeElement).click();
}
});
Why does this alert fire twice when you hit tab to focus the button and enter for the keypress event, but only fires once when you click the button with the mouse?
Demonstration
EDIT: tab + enter doesn't work at all in IE 10
Because hitting "Enter" when focus is on a button triggers the "click" event natively. You also get a "keypress" event, and from that you trigger the "click" event again.
I know it's an old post but while I was looking for a solution of a nearly identical problem I've found out that the default type of a <button> element is "submit".
This means that if you press Enter anywhere in the <form> containing this button, it will automatically submit.
Actually, if you press enter in any of those two input, the snippet closes. If you define a function to click a button on the Enter keypress event it will trigger twice unless you add a "button"to the button element, because you trigger it both with your function and the automatic submit.
TLDR:
add type="button" to your button element.
$(document).ready(function(){
$(document).on('click','#submit_type',function(){
console.log($(this).attr('id'))
});
$(document).on('click','#button_type',function(){
console.log($(this).attr('id'))
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
<input>
<button id ="submit_type">Can enter</button>
</form>
<form id="form2">
<input>
<button type="button" id="button_type">Cannot enter</button>
</form>
I'm responding here to Pointy's comment instead of in the comments due to lack of space;
I can confirm that I can see the click getting triggered in the JSbin, but I am not sure how to account for the difference between my actual application code's behavior and that on the page. Perhaps it was because I bound my "click" on a separate line instead of chaining it.
I have not yet learned how to use JSBin, but I make a solemn promise to do this soon. However, my info came from experimentation in my own code:
$(settings.selectors.patientSearchSubmitButton).click(validatePatientSearch);
Was followed by
$(settings.selectors.patientSearchSubmitButton).click(alertOnClick);
I also had another binding:
$(settings.selectors.patientSearchParameter).keypress(function (e) {
if (e.which == 13) {//Enter key pressed
validatePatientSearch();
}
});
patientSearchParameter was a field next to the button. When I focused on the field and hit "enter" in chrome, ff, plain IE11, the validatePatientSearch function ran once, and the alertOnClick function did not run. When I did the same thing in IE11 compatibility mode for IE8, 9, 10; the function ran twice, and the alertOnClick was triggered. I am not certain how I could prove it, but this has been my experience, and this was repeated behavior over 20 or so test tries. I am using Windows 7 64 bit. Not sure what else could be causing it to behave this way, but I hope it can be useful to someone.
Could it be because my click was bound to the button and not the field?

Preventing an event before other callback finished

I have an application that uses backbone.js and jQuery for UI. I have a form on a page, attached to the form's text box blur event is a function that under certain conditions shows the user a popup and awaits it's input - the conditions are checked using an ajax call to a WCF service.
Everything works fine until i click the form's submit button while the focus is set on the text field - then the popup is displayed but behind it the form is submitted.
Of course the proper result would be cancelling the second event(if the popup is displayed the form definitely cannot be submitted)
How can I achieve this?
i can'T understand you but probably this is what you need: event.stopPropagation();
http://api.jquery.com/event.stopPropagation/
Or .off()
http://api.jquery.com/off/
You can bind to the submit event of the <form> and call its preventDefault() method to inhibit submission if the popup is visible:
$("form").submit(function(e) {
if ($("selector_matching_your_popup").is(":visible")) {
e.preventDefault(); // Cancel submission.
}
});
You can also return false from the handler instead of calling preventDefault(), but this will also stop the propagation of the submit event to ancestor elements, which you may not want.
Are you saying that the clicking of 'submit' is causing the popup to display - and this is not one of the 'certain conditions' where it should be displayed? I would consider adding a condition to the blur handler that checks to see if the submit button was clicked. Dont display the popup in this case.
Cancel the event in the onSubmit handler -
form.addEventListener("submit", function(evt){
evt.cancel()
//dont want to catch it again
form.removeEventListener(this)
popup.show()
//have the popup call submit when done, it wont be caught again
}

Keyup event firing, change event not

I am building a bunch of controls dynamically.
Essentially I am attaching a keyup to the textbox to detect when up/down is pressed in a table to move between cells. I am also watching for when the input field changes, because I then add that control to an array for posting back when the user hits save.
This works when I tab between controls or click from one control to the next. However, If I use the arrow keys as coded to move between fields, the change event does not fire.
My event handling code looks like this:
$('input[id^="reo_"]').bind('change', function () {
rowDetailChange($(this));
});
$('input[id^="reo_"]').bind('keyup', function (e) {
processKeyUp($(this), e);
});
The change event fires upon focus out, blur and enter with the condition that the content has been altered. This is because the event would fire a great lot elsewise.

Capture "done" button click in iPhone's virtual keyboard with JavaScript

I'm wondering if there's a way to capture the iPhone's virtual keyboard's done button event, using JavaScript?
Basically, I just want to be able to call a JS function when the user clicks done.
I was unable to track the 'done' button being clicked. It didn't register any clicks or keypresses. I had to addEventListeners for change, focusout and blur using jquery (because the project already was using jquery).
You need to do some kind of this:
$('someElem').focusout(function(e) {
alert("Done key Pressed!!!!")
});
It worked for me, hope it will help you as well.
After searching and trying this solution
basically is say:
document.addEventListener('focusout', e => {});
tested on IPhone 6s
This question is kinda old, but I've found a hacky way recently to make this working.
The problem with the 'blur', 'focusout' events is that they fire even if user just tapped outside the input/textarea, and did not press the 'Done' button, in my case, UI should behave differently depending on what exactly have happened.
So to implement it, I've done the next thing:
After showing the keyboard (the input received the focus), add click handler on the window via the addEventListener function. When user clicks on the window, remember the timestamp of the click in the variable (let's call it lastClick = Date.now())
In the blur event handler, set a timeout for 10-20 ms to allow other events happening. Then, after the timeout, check if the blur event happened in a time difference lower for example than 50-100 ms than the lastClick (basically Date.now() - lastClick < 50). If yes, then consider it as a 'Done' button click and do corresponding logic. Otherwise, this is a regular 'blur' event.
The key here is that tapping on keyboard controls (including Done button) does not trigger the click event on the window. And the only other way to make keyboard hide is basically tap on other element of the page and make the textarea lose focus. So by checking when the event happened, we can estimate whether that's a done button click or just blur event.
The answer by oron tech using an event listener is the only one that works cross platform.
document.getElementById("myID").addEventListener("focusout", blurFunction);
function blurFunction() { // Do whatever you want, such as run another function
const myValue = document.getElementById("myID").value;
myOtherfunction(myValue);
}
"Change" event works fine
document.querySelector('your-input').addEventListener('change',e=>
console.log('Done button was clicked')
);
attach a blur event to the text box in question. The done fire will fire this event.
The done key is the same as the enter key. So you can listen to a keypress event. I'm writing this using jQuery and i use it in coffee script so I'm trying to convert it back to js in my head. Sorry if there is an error.
$('someElem').bind("keypress", function(e){
// enter key code is 13
if(e.which === 13){
console.log("user pressed done");
}
})

Categories

Resources