I have a simple search page with a single input box.
I want to be able to trigger the search action either by clicking "Go" or by pressing Enter in the input box. I did it like this:
$("input[name='entry']").keyup(function (event) {
if (event.keyCode == 13) {
search_phone();
}
});
$('a#go').click(function () {
search_phone();
});
Is there a more elegant way to do this? Like with bind and trigger, or fling. If so, how?
Not much can you improve here. Your code is pretty good.
You could skip the anonymous function for the click event.
$('a#go').click(search_phone);
I would just make your "go" link the submit button
<input type="submit" name="submit" value="go"/>
And then just bind your function to the submit (which would happen either from pressing enter while in the text box or by clicking the go button.
$('#my_form').submit(search_phone);
Related
Below is a code that redirects people to a page of the same name. For example, if I type in the word 'chocolate' and click 'Submit', the user should be redirected to a page of the same name called 'chocolate.html', etc.
This code only works when the <form> parameter tag is removed, and if removed involves manually clicking the [Submit] button to be redirected to the .html page of the same name (rather than redirecting when pressing [Enter] or [Return] key on the keyboard).
This code does not work when I add the <form> parameter tag; it only works if removed. I've been meddling with this for hours to get it to work with the <form> tag. Any ideas?
This is the code:
Note: If you remove the form tag, it works, but only when you click the 'Submit' button manually.
This is what I got so far, I now only need the button to automatically click when the person presses the Enter key on their keyboard. :)
UPDATE: Firstly, thank you so kindly for your help so far.
UPDATE: The code now successfully redirects to a .html page of the same name, but the user needs to manually clicks the [Submit] button to accomplish this. From here, I am simply needing to find a way of having the [Enter] button automatically be selected/clicked whenever the user presses [Enter] on their keyboard. :)
<input id="test" type="text" autofocus>
<button type="button" onclick="redirect()">Submit</button>
<script>
function redirect()
{
var url=document.getElementById('test').value
window.location = url+".html"
}
</script>
Add a type attribute to your button like so:
<button type="button" onclick="redirect()">Submit</button>
By default, if not set, the type of a button is assumed to be submit and will therefore submit your form to the action provided in the form's action attribute. Setting the type attribute to button prevents this default behaviour.
Seeing that you have no action attribute specified in your form, the current page is assumed as the action to redirect to so the form essentially reloads the current page.
This is something new. Anyway the thing is when you are keeping the form tag there it is with no action attribute keeping you in the same page. When form tag is there you can not hit the script for the redirect.
When you are removing the form tag it is hitting the JS and activating the code. Seeing the form tag I am assuming that you are trying to send some data.
It is advised that you use jquery and ajax to manipulate these data. Or you can discuss more.
Add this after your function:
var test_keydown = document.getElementById("test");
test_keydown.addEventListener("keydown", function (e) {
if (e.code === "Enter") { //checks whether the pressed key is "Enter"
redirect();
}
});
I got your problem, basically, you want to trigger redirect function when the user clicks submit button or if the user presses the ENTER key on the keyboard.
You can do this 2 ways -
If you want the user to redirect when he press enter key anywhere on the page, then you need to add keyup event on the document object, see below code -
It will trigger redirect function when the user clicks the ENTER key on the keyboard.
<input id="test" type="text" autofocus>
<button type="button" onclick="redirect()">Submit</button>
<script>
function redirect()
{
var url=document.getElementById('test').value
window.location = url+".html"
}
document.addEventListener("keyup", function(event) {
if (event.keyCode === 13) { //13 is enter keycode
event.preventDefault();
redirect();
}
});
</script>
Another way is to add keyup event on the input itself and then call the redirect function. This is when you don't want to trigger redirect on the whole document, but only when the user is done typing in input and then presses ENTER.
<input id="test" type="text" autofocus onkeyup="handleKeyUp(event)">
<button type="button" onclick="redirect()">Submit</button>
<script>
function redirect()
{
var url=document.getElementById('test').value
window.location = url+".html"
}
function handleKeyUp(event) {
if (event.keyCode === 13) { //13 is enter keycode
redirect();
}
}
</script>
If you want to do this in form tags handle the on submit event instead. This will also handle the enter keypress at the same time as that is the default behavior in a form.
//Add the evnent listener unobtrusivly
document.getElementById("redirector").addEventListener("submit", function(event) {
//Stops the form submitting (its' default action)
event.preventDefault();
//Get the location
var redirectTo = document.getElementById('test').value + ".html"
//bit of debugging
console.log("Redirecting to: " + redirectTo)
//redirect
window.location.href = redirectTo;
})
<form id="redirector">
<input id="test" type="text" autofocus>
<!-- Note this will now submit -->
<button>Submit</button>
</form>
You should use
document.addEventListener('keyup',function(e) {submitButton.click()})// submitButton is `document.getElementById('<idOfsubmitButton>')`
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.
I have an application that already in use.
I need to add few hotkeys to it like Enter should trigger some already existing Button.Click events.
It has multiple forms.
1st form has
<button name="Search" type="button" class="abc" disabled>Search</button>
2nd on has
<button type="button" class="xyz" id="show" ">Show</button>
3rd ....
The button click events are in a .js file
$('body').on('click', '#search-form button[name=Search]', function () {
//implementaion
});
$('body').on('click', '#Show-Change', function () {
//implementaion
});
Now when I am using the Search form , its has multiple drop-downs to be selected.
When I press enter the Search.Click should be triggered (should behave same as when I click on the SEARCH button), when I am using the 2nd form the show, the click event should trigger.
The first form is like a menu form on the left side of the form. The second one is a popup form. I am new to .js and need help. I need to implement these on couple of similar forms in the application.
$(document).keypress(function (e) {
if (e.which == 13) {
$('#search-form button[name=Search]').click();
}
});
But this works only for the search.click button, and is triggered whenever Enter is pressed, irrespective of the form I am on.
Not sure how to make it generic enough to handle this on every form that needs enter as a Hotkey.
I'm trying to display the require popup when a certain input is not filled or isn't filled correctly in my form. So, for doing this, I've created this form:
<form id="login">
<input class="form-control require" type="email" placeholder="username" ></input>
<button type="submit">
go
</button>
</form>
and I put the logic inside a js function:
$('#login').submit(function(event)
{
event.preventDefault();
$(event.target).find('.require').each(function()
{
if($(this).val().length == 0)
{
this.setCustomValidity("Field Required!");
}
else
{
this.setCustomValidity('');
}
});
console.log('ajax execution');
});
Now how you can see when the form is submitted I prevent the default event submit, and assign to each control a custom validation error. Now the problem's that if a field is not valorized correctly, for example is blank I get no popup displayed, instead, if I press again the submit button I can see the require popup appear on the UI.
Someone could help me to fix this?
I put an example JSFIDDLE here.
When you press the button for the first time no popup appear, the second time appear correctly but, this should appear the first time or anyway, each time that a particular field is not valid.
if($(this).val().length == 0) this code will not properly if the input field has only space . To avoid that u should use this:
if($.trim($(this).val()).length == 0)
OR
if($.trim($(this).val()) == "")
Your problem seems to be that the submit event is only firing once. I'm not familiar with bootstrap, so I haven't seen the setCustomValidity function before but I would guess that it is probably attaching its own listener, which is prevent the button click from triggering the submit at all.
I notice that if I type something into the text box, and fire setCustomValidity on it, it says "please enter an email address" - which I don't see in your code. If I then enter 'asdf#qwer.dfsgh', it gets validated and submits.
So it looks like you have not understood how setCustomValidity is supposed to be used. I would guess, you are probably supposed to attach it once, when the page first loads, and not repeatedly as you are doing.
I am using the following html
<input type="button" value="Get" onClick="get();">
get(); it is some function declared earlier using javascript
I know if the input type is submit it works, but how to make it work for the following?
Enter on Key Board.
get function
function get() {
$.post('ass.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
}
What are you trying to do is against standards: http://www.w3.org/wiki/HTML/Elements/input/button "The button state represents a button with no default behavior."
The only solution is to catch keyPress action, with appropriate button code.
jQuery has a keyup method, but I'm not sure it will do what you want -- it will detect whether a key has released when the button has focus. The only way to intercept the enter key and prevent it from making the form submit will be to use submit.