Using jQuery to trigger Enter event - javascript

I have an image tag :
<img src='Presale.png' alt='presell' onclick="presell()"/> Presell
Function :
function presell()
{
$(".form-control").val("presell");
var e = jQuery.Event("keypress");
e.which = 13;
e.keyCode = 13;
$(".form-control").trigger(e);
}
What I wanted to do was to fill a search box with some text and trigger enter the moment a particular image is clicked so that search related to that image is made. But this code is putting the value to the search box but not triggering enter.

You need to submit the actual form, instead of triggering a keypress event with enter's keycode (does not work)
e.g.
$("form").submit();

You can do it like this:
<img src='Presale.png' alt='presell' /> Presell
<form>
<input type="text" class="form-control" />
</form>
Note: I removed the click handler from the image.
And in the JS:
$("img").on("click", function(){
$(".form-control").val("presell");
$("form").submit();
});
Demo

I assume what you need is to simulate a 'return/enter' key press which would most naturally submit the value of the input (which can be via submit/AJAX)
.trigger() would call the eventhandler and not simulate the native browser event. Refer: http://learn.jquery.com/events/triggering-event-handlers/
You would then need to bind an event handler to the enter keypress and provide what is to be done anyway. Which means including .submit() or post() or $.ajax() or whatever code that is called (unless it is defined on a trigger handler)
What you probably need is .simulate(); available via jquery.simulate.js

Related

Why cant I press enter programatically?

I'm trying to fire off a search programatically having populated the input.
Can't find a clear Javascript example of that though. Jquery not really an option as i want to keep this a lightweight Chrome Extension.
Emitting the 'Enter' event just seems to return a true with no search actually beginning.
HTML
<form id="form">
<input type="text" placeholder="Search Foo" />
</form>
Javascript
const input = document.querySelector(`input[placeholder="Search Foo"]`);
// ^^ targets element successfully
input.value = "this is my search term";
// ^^ adds value to input fine.
input.dispatchEvent(new Event('focus'));
// ^^ appears to focus correctly
input.dispatchEvent(new KeyboardEvent('keyup',{'keyCode': 13}));
// ^^ returns 'true' in console but nothing happens.
const form = document.getElementById("form");
form.submit();
// ^^ triggers a full page refresh, not an 'enter' / submit action.
I have tried a few variations around this (deprecated KeyEvents syntax mostly).
Why can't I actually fire off 'Enter' / submit on the input/form?
You could also put the input in a form element and then call form.submit() on the form element.
Pressing even is triggering an event you need to find what event the code is listening to the below would work for keyup event
var evt = new CustomEvent('keyup');
evt.which = 13;
evt.keyCode = 13;
input.dispatchEvent(evt);
Have a look at this answer it might help https://stackoverflow.com/a/29720843/13335890

Submitting Form on Enter Press

I know that this question has been asked before but I'm having particular trouble submitting my form when I press the enter key. I've tried multiple solutions but none have worked. When I try to press enter, the page refreshes and my typing is gone.
This is my HTML:
form class="nput">
<h1 class= "header">Member Login</h1>
<label class="text" for="pswd">Enter your password: </label>
<input class="form" type="password" id="pswd">
<input id="yeet" class="bttn" type="button" value="Submit" onclick="checkPswd();" />
</form>
And this is my Javascript:
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "password";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location="members.html";
}
else{
alert("Password incorrect. Please try again.");
}
}
// Get the input field
var input = document.getElementById("pswd");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
alert("hi there");
event.preventDefault();
document.getElementById("yeet").click();
}
});
</script>
I cannot figure out this small issue and I would appreciate any help! Thanks!
EDIT: I just wanted to let everyone know that I do in fact know that there is little security that comes with this method but I mostly want the password for looks not function.
You got something backwards there - you are submitting the form with Enter. This is exactly the problem though, it seems as if you don't want to submit it, instead you want to run your client-side handler checkPswd. (You do know that everyone can read the correct password in their browser console though, right? So it's no protection.)
What you want to do is change the onclick on the button to an onsubmit on the form itself! Then your code will run no matter in what way (keyboard or mouse) the form is submitted.
You can delete the whole keyup stuff then.
(The reason your attempt to "click" the button in JavaScript wasn't working is because unlike jQuery's click method, the vanilla click will only execute the default action and not any attached click event handlers like yours. Also, it is kinda backwards because you should react on the common ground of both clicking the button and pressing Enter, which is submitting the form.)
To echo a comment above - you want to use the onsubmit handler on the <form> element - this will allow users to submit the form both by clicking the <button type="submit> button, and by hitting the enter key in one of the forms <input> elements.
You can probably ditch the input.addEventListener("keyup", function(event) {...} altogether by just using the obsubmit handler.
You can learn more about the HTML <form> element's onsubmit behavior here:
https://www.w3schools.com/tags/ev_onsubmit.asp
No need to put handlers on button element. You should use either input type as submit or button type as submit. onsubmit handler can be given to form element where you can actually prevent default event and go ahead with password validation .
Hope this gives you an idea.
If I were you, I would do two things:
1) I would check the Chrome debugger to see if there are any issues with your code
2) Instead of input.addEventListener("keyup", function(event) {, I would try input.onkeyup = function(event) { and see if that works.
Hope this helps.

Javascript - Can I run my event handler AFTER the default handler for the "onkeypress" event?

I have an input text and I want to run my function after the default event handler
<input type="text" onkeypress="myfunction()"></input>
the function
function myfunction(){alert($("input")[0].value)}
because myfunction() is using the input value and this property will be changed after the default handler runs and change it.
Example: if the text field has value "1234" , and I pressed the key "5", the function will alert "1234" not "12345"
So, I want the default function runs first to change the value property , then I can use it in myfunction()
can I do something like this ?!
onkeypress="default();myfunction()"
I did a work around by putting myfunction() in the onkeyup event, but I don't want that.
Thanks, and please consider I'm very newbie.
TRIVIAL SOLUTION:
You should use oninput instead of onkeypress. Like so:
<input type="text" oninput="myfunction(event)" />
The keypress event is emitted when a key gets pressed, i.e., before the DOM is modified with the pressed key's value. This is why you never got the value of the last key pressed.
The input event is emitted when data is entered into the input element. So we can access the data by reading the value of the element.
USING EVENT-BINDING:
HTML
<input id="input_field" type="text" />
jQuery
$(document).ready(function() {
$("#input_field").on("input", function() {
console.log($(this).val());
});
});
Pure JS
var input_field = document.getElementById("input_field");
input_field.addEventListener("input", function(event) {
console.log(event.target.value);
});
NOTE: Add this in a script tag after the HTML or use window.onload to simulate the behaviour of $(document).ready.
See this SO answer for more information about how event-binding works.

In a form with 2 buttons - how to choose which button the "Return" key activates?

I have a form with 2 buttons - one is the submit button and the other is a button to apply a discount code. The problem is the Return key always activates the submit button at the bottom of the form.
Is there any way to have the Return key activate the discount code button when the discount code text field is active?
The long and the short is that you'll need to capture either the keyboard event or the submit event of the form. Personally, I think you're better off with keyup.
var discountInput = document.getElementById('discount-input');
var form = document.getElementById('my-form');
function keyupHandler(evt)
{
if(evt.keyCode == 13 && document.activeElement == discountInput)
{
evt.preventDefault();
evt.stopImmediatePropagation();
// either trigger the event handler which adds the discount,
// or call that function here.
}
}
form.addEventListener('keyup',keyupHandler);
Check out this thread:
Trigger a button click with JavaScript on the Enter key in a text box
basically, you attach a key-up listener to the button you want to respond.
Use autofocus attribute
<input type = "submit" autofocus>

When editing a text input, how do I do a specific JavaScript action on hitting "Enter" key without the form's onSubmit handler?

I have an HTML input text field.
How can I perform a specific JavaScript call when hitting "Enter" button while editing that field? Currently, hitting "Enter" reloads the entire page, presumably due to submitting the entire form.
NOTE: This HTML/JS code is merely included as a portlet into a large HTML page for a portal, which has one large master form wrapped all the way around my code. Therefore I can not control the form - can't change onSubmit event or action or wrap my INPUT field into a smaller form - otherwise the solution would be obvious :)
Also, a solution that does not involve adding a visible button to the form is strongly preferable (I don't mind adding a button with display:hidden if that's what it takes, but my attempt to do so didn't seem to work).
This needs to be straight up JS - no Query/Prototype/YUI is available.
P.S. it's a search field and the action will be a call to an existing in-page JavaScript search method, if someone's curious.
Thanks!
Assuming you have a text input something like
<input id="myTextBox" name="foo" value="bar">
... you could do something like this, after the document has loaded, and it will work in all mainstream browsers:
document.getElementById("myTextBox").onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
if (charCode == 13) {
// Suppress default action of the keypress
if (evt.preventDefault) {
evt.preventDefault();
}
evt.returnValue = false;
// Do stuff here
}
};
Include the following javascript
<script type="text/javascript">
function noenter() {
return !(window.event && window.event.keyCode == 13);
}
</script>
Add the following attribute into the input element that you wish to prevent the submit
onkeypress="return noenter()"
Of course you can perform some other event if you wish...
Would you be better off using the document object to detect the Enter action? That way you need make no changes to the HTML form tags. You can assign the search function to the button, although if it's hidden I am not sure how the user would click on it, or you could use something like onblur to capture the user tabbing out of the input control.
Try adding an attribute "action=javascript:void(0)" as in the example below.
Enter will trigger the same action as clicking on the submit button, but won't reload the page automatically.
<html>
<head></head>
<body>
<div id="status"></div>
<form action="javascript:void(0)">
<input type="text" />
<input type="submit" value="submit" onclick="document.getElementById('status').innerHTML = 'submitted';"/>
</form>
<script>document.getElementById('status').innerHTML = 'page loaded';</script>
</body>
</html>

Categories