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
Related
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.
Have been searching for a solution to this problem for 2 days now and none of the suggested solutions have worked so far.
My form html is defined with
<form id="quote_form" action="" method="get" class="ui large form">
and input text fields in the form
<input v-model="city" type="text" name="quote[city]" id="city">
I have been trying to isolate the cause of the issue but have not been able to do so. I tried turning off the keyboard shortcuts settings for semantic ui forms:
$('.ui.form').form({
keyboardShortcuts: false
});
I have also tried to override the enter key and prevent it from triggering the submit function in these ways:
$('#quote_form').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.stopPropagation();
e.preventDefault();
return false;
}
});
$(document).on("keypress", "form", function(event) {
return event.keyCode != 13;
});
$('#quote_form').bind('keypress keydown keyup', function(e){
if(e.keyCode == 13) { e.preventDefault(); }
});
The form has multiple steps in filling it in. Each step uses a button to permit the advance to the next step. When enter is pressed then it causes the form to redirect to the first step/tab of the form. The only case where it doesn't redirect is when the rules of the current step are not satisfied. The form submission is handled by a submit button where the button itself calls methods to validate and submit the form. I can't find any connection between enter submit behaviour and the button for submitting.
If I am missing any useful information to help isolate the cause then please let me know. I'm new to asking questions here and want to prevent my question from being considered bad as much as possible :)
Here is solution for you:
#submit.prevent
https://jsfiddle.net/4qpffycs/2/
Just use #keyup.enter.prevent at the end of the input markup. See VueJS Doc
By the way, you should try to use native VueJS Events instead of all redoing it with JQuery
The solution I found regards only Semantic UI without VueJS, but should be applicable here and gives a bit of an insight into the issue.
The problem arises from the fact that $("#formId").form({ ... }) registers an event handler for a button press and submitting the form on Enter press if one of the input boxes are selected. This can be seen in Chrome DevTools when selecting the element and choosing Event Listeners category:
The simplest way I found to remove this behavior is to call
$("#formId").unbind('keydown')
to remove the keydown bind completely from the element.
I'm working on a site that prevents backspace in an input field by default, but for this particular input, I would like to return it to its default behaviors to accept backspace.
What is the simplest way to do this? Basically I need the opposite of preventDefault().
Update: I added the following message in the comment but thought it's important to the question. So here it is:
Unfortunately, I have no idea how it prevents the backspace. I'm creating a Chrome extension which injects an input field into the page. Everything works except the backspace. I tried to find the code where it prevents it but it's impossible.
My code to create the field is this:
if(!document.getElementById("input_typing")){
var input = document.createElement('input');
input.id = "input_typing";
input.tabIndex = 1;
input.style.width = "95%";
input.focus();
txts[i].parentNode.appendChild(input);
}
My idea is: there could be an handler attached to the document so that *site that prevents backspace *.
I'm not sure of this, but I created a snippet to clarify my idea:
if an event handler prevent the default action on backspace you may add a new event handler for your newly created input field in order to stop propagation.
//
// Let's assume this is the site handler to prevent backspace
//
document.addEventListener('keydown', function(e) {
if (e.which === 8) {
e.preventDefault();
}
});
//
// your new element
//
if(!document.getElementById("input_typing")){
var input = document.createElement('input');
input.id = "input_typing";
input.tabIndex = 1;
input.style.width = "95%";
input.focus();
document.querySelectorAll('input[type="text"]')[0].parentNode.appendChild(input);
//
// Add the keydown event handler to stop propagation
//
input.addEventListener('keydown', function(e) {
e.stopPropagation();
});
}
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
In Case if it is JavaScript file which prevents the backspace :
You can do inline scripting in your page directly after the js file (which contains code to prevent the backspace in input filed) is added.
So that the JS will be included - it will disable backspace.
Post this when you do your inline scripting to enable the previous functionality - your script code will override the included js
In Case if it is CSS file which prevents the backspace :
You can use inline css scripting with !important at the end of each line so that this will override the existing css.
Note : It would be best to add your css/js inline scripting code at the end of the page to provide certainty and avoid confusions.
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
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>