Capturing 'enter' key on input not working - javascript

I'm going crazy trying to figure out why this isn't working... I have a text field and I want to capture when someone pushes enter so that the 'next' button can be focused.
This is more or less the input with id of 'guess'.
<input type='text' size='30' id='guess' autocomplete='off' value='' onMouseOver='javascript:this.focus();'>
I've added this event listener, but it's not activating...
document.getElementById('guess').addEventListener('keydown', focusnextbutton(event));
function focusnextbutton(e){
alert('you pushed a button');
if(e.keyCode == 13){
// alert('Button was enter');
// document.getElementById('next_btn').focus();
}
}
The 'you pushed a button' alert isn't even coming up and I cannot work out why. Help? I'm using Chrome on Ubuntu if that's relevant.

Not sure why it's not working either but if you change the line to:
document.getElementById('guess').addEventListener('keydown', focusnextbutton,false);
it will work fine

You have to remove the brackets after the focusnextbutton function.
document.getElementById('guess').addEventListener('keydown', focusnextbutton);
This is because the second argument of addEventListener is a function to call. When the code is run for the first time, addEventListener runs the second argument immediately and expects a function to be returned for the argument. For example, you could also do:
document.getElementById('guess').addEventListener('keydown', function(){
focusnextbutton(event);
});
The anonymous function as the second argument is a function definition and therefore is not run when the code is first evaluated, but IS run on keydown.
You will notice that the alert 'you pushed a button' is run immediately when the page loads. This is because the function is called while the event listener is being added and was key for debugging this error.

Try this
document.getElementById('guess').addEventListener('keydown',function(event){
focusnextbutton(event);
});
Pass the event argument to the callback function too. That's what's missing from the previous answers.
Fiddle Link

Related

2 JavaScript events triggered sequentially - 2nd one ignored

I have an input text box and a button on a page.
have an onchange event on the text box and an onclick on the button. Each event triggers a totally separate unrelated method.
The problem is as follows:
if the user makes changes to the text box, then right away goes to click on the button - the onchange is triggered but I lose the onclick.
can I avoid this? I need both events to happen.
Thanks
Updated:
I tried a very simple test locally:
<input type="text" onchange="alert1();"/>
<input type="button" onclick="alert2();"/>
where the js is :
<script type="text/javascript">
function alert1()
{
alert("1");
}
function alert2()
{
alert("2");
}
</script>
changing the text and right away clicking on the button only triggers the first event. Is there a way to force the second event to happen?
An alert (along with other modal dialogs) is a bit of a special case, since it suspends execution of the remainder of the script until the user clicks OK. This is why your second handler falls through the cracks.
If you did something like document.write('foo') in your handlers instead, you wouldn't have this problem.
Try this,
function showAlert1() {
setTimeout(function(){ alert("ONE") }, 250);
}
function showAlert2() {
setTimeout(function(){ alert("TWO") }, 250);
}​
It buffers the execution of each function so that the button's onclick can be triggered.

JavaScript function that creates HTML form and returns user input

I want to create a JavaScript function that will create an HTML form and return the input the user enters into the form. My stupid first attempt was something like this:
function getInput() {
$('#somediv').html( "<input type='button' id='mybutton' name='Click Me'></input>" );
$('#mybutton').click( function() { return "result"; } );
}
result = getInput();
alert( result );
(The actual situation is more complex, the user has to first enter some text and then choose between several different buttons, and the return value depends on the entered text and the chosen button, but I think those are peripheral issues so I left them out). If I run this as written, I'll get alert "undefined" where what I want is alert "result". Essentially I want the function not to return until it's explicitly told to do so. Is there any way to achieve this? If not, what's the simplest workaround that's similar in spirit to the above?
A very similar question was posed here: JavaScript pausing execution of function to wait for user input. I'm afraid I just couldn't understand the responses well enough to adapt them to my particular case. Perhaps someone could advise how to do so, or alternatively starting from scratch would be fine too.
It is impossible to wait for user input in a form like that. You need to break it up in two parts to handle the asynchronous request.
function getInput(callback) {
$('#somediv').html( "<input type='button' id='mybutton' name='Click Me'></input>" );
$('#mybutton').click( function() { callback("result"); } );
}
function processInput (result) {
alert(result);
}
getInput(processInput);
I think what your looking for is event delegation, using event delegation you can bind your function to your #mybutton before your button is even added to your form.
For example using .on()
$(document).on('click', '#mybutton', function() {
//your code here
});
The basic idea behind event delegation is to take advantage of the fact that in JavaScript events bubble up, so what you do is bind the event to a higher element in the DOM and then check to see where it originating from, so long as the higher level exists at the time you bind the event your OK.

Is there a way to capture the alert ok button click event?

Is there a way to capture the alert ok button click event? In jQuery?
The alert() function is synchronous and you can't verify what was clicked (it does not return anything), so the code below the call will be executed after it is closed (ok or close button). The alert is not used to gain user input. It is an alert, a message to the user. If you need to check what the user want, you should use confirm(). Note that the function name tells its purpose like alert.
Something like:
// if the ok button is clicked, result will be true (boolean)
var result = confirm( "Do you want to do this?" );
if ( result ) {
// the user clicked ok
} else {
// the user clicked cancel or closed the confirm dialog.
}
Alert is a blocking function, means, if you don't close it, the code below will not execute.
So you don't have to capture the alert close event, just write down the code below that alert, when alert window will be closed the code below will be executed automatically.
See example below:
alert("Close Me");
// Write down the code here, which will executed only after the alert close
console.log("This code is executed after alert")
Disclaimer: This is a very bad thing to do.
Technically you could hook into it with this code:
window.alert = function(al, $){
return function(msg) {
al(msg);
$(window).trigger("okbuttonclicked");
};
}(window.alert, window.jQuery);
$(window).on("okbuttonclicked", function() {
console.log("you clicked ok");
});
alert("something");
​
Demo: http://jsfiddle.net/W4d7J/1/
There is no event for the window.alert(). Basically the next line after it is called when they click ok. I am not sure why you would need to listen for it.
I tried this in a site I created and it worked perfectly :
<< Back
You could use JAlert and assign a click handler to the ok button.
Something like
jAlert("Alert message goes here.");
$('#popup_ok').bind('click',function(){
//Do operation after clicking ok button.
function_do_operation();
});

How do I properly capture an onchange or onkeyup event for a dynamically inserted 'input' text element?

I have a bit of JavaScript that builds some HTML for me and inserts it into a div. I am using jQuery 1.7.2 for this test.
I'm interested in attaching a custom change or keyup event handler on an input text field called gene_autocomplete_field.
Here's what I have tried so far.
The following function builds the HTML, which is inserted into a div called gene_container:
function buildGeneContainerHTML(count, arr) {
var html = "";
// ...
html += "<input type='text' size='20' value='' id='gene_autocomplete_field' name='gene_autocomplete_field' placeholder='Enter gene name...' /><br/>";
// ...
return html;
}
// ...
$('#gene_container').html( buildGeneContainerHTML(count, geneNameArr) );
In my calling HTML, I grab the gene_autocomplete_field from the gene_container element, and then I override the keyup event handler for gene_autocomplete_field:
<script>
$(document).ready(function() {
$("#gene_container input:[name=gene_autocomplete_field]").live('keyup', function(event) {
refreshGenePicker($("#gene_container input:[name=gene_autocomplete_field]").val());
});
});
</script>
When I change the text in gene_autocomplete_field, the refreshGenePicker() function just sends an alert:
function refreshGenePicker(val) {
alert(val);
}
Result
If I type any letter into the gene_autocomplete_field element, the event handler seems to call alert(val) an infinite number of times. I get one alert after another and the browser gets taken over by the dialog boxes. The value returned is correct, but I worry that refreshGenePicker() gets called over and over again. This is not correct behavior, I don't think.
Questions
How do I properly capture the keyup event once, so that I only handle a content change to the autocomplete field the one time?
Is there a different event I should use for this purpose?
UPDATE
It turns out that more than just a keyCode of 13 (Return/Enter) can be an issue — pressing Control, Alt, Esc or other special characters will trigger an event (but will be asymptomatic, as far as the infinite loop issue goes). The gene names I am filtering on do not have metacharacters in them. So I made use of an alphanumeric detection test to filter out non-alphanumeric characters from further event handling, which includes the Return key:
if (!alphaNumericCheck(event.keyCode)) return;
alert is called infinite times because you use the 'Enter' key to confirm/dismiss the alert. Use .on('change') instead. This will prevent refreshGenePicker from being called when you use enter in an alert.
JSFiddle demonstration using keyup (Click on OK to prevent infinite alerts).
JSFiddle demonstration using change
However, the 'change' event will only trigger if the input element looses focus. If you want to use refreshGenePicker on every key, use the following approach instead:
$("#gene_container input:[name=gene_autocomplete_field]").live('keyup', function(event) {
if(event.keyCode === 13) // filter ENTER
return;
refreshGenePicker($("#gene_container input:[name=gene_autocomplete_field]").val());
});
This will filter any incoming enter keyup events (jsFiddle demo). Also switch to .on and drop .live.
EDIT: Note that there are more possibilities to dismiss an alert modal, such as the escape or space key. You should add a check inside your refreshGenePicker whether the value has actually changed.
You should really use .on() if you are using jQuery > 1.7.
Check out the perftest.
And also check out my some what related question.
Also when testing equal you should really add quotes around it:
input:[name='gene_autocomplete_field']
To answer you real question :). It shouldn;t behave like that with the code you have presented. Maybe something else is wrong. Can you setup a jsfiddle with the issue?
Check out my demo and perhaps you see what's wrong with your code:
function refreshGenePicker(value) {
console.log('keyup! Value is now: ' + value);
}
(function($) {
var someHtml = '<input type="text" name="gene_autocomplete_field">';
$('body').append(someHtml);
$('body').on('keyup', 'input[name="gene_autocomplete_field"]', function(e) {
refreshGenePicker($(this).val());
});
})(jQuery);​
$(document).ready(function() {
$('#test').html('<input id="text" />');
$('#text').keyup(function() {
console.log($(this).val());
});
});​
This works just fine. Since you've got our second code block in <script> tags, you might be running it more than once - which would cause it to bind more than once and produce more than one alert each time it is bound. You could of course use .unbind() on that input before adding the keyup, but I think a much better solution would be to group all the code in a single $(document).ready(); to ensure you're only binding the object once.
http://jsfiddle.net/Ka7Ty/2/

Why is my onchange function called twice when using .focus()?

TLDR
Check this example in chrome.
Type someting and press tab. see one new box appear
type something and press enter. see two new boxes appear, where one is expected.
Intro
I noticed that when using enter rather then tab to change fields, my onchange function on an input field was firing twice. This page was rather large, and still in development (read: numerous other bugs), so I've made a minimal example that shows this behaviour, and in this case it even does it on 'tab'. This is only a problem in Chrome as far as I can tell.
What it should do
I want to make a new input after something is entered into the input-field. This field should get focus.
Example:
javascript - needing jquery
function myOnChange(context,curNum){
alert('onchange start');
nextNum = curNum+1;
$(context.parentNode).append('<input type="text" onchange="return myOnChange(this,'+nextNum+')" id="prefix_'+nextNum+'" >');
$('#prefix_'+nextNum).focus();
return false;
}
HTML-part
<div>
<input type="text" onchange="return myOnChange(this,1);" id="prefix_1">
</div>
the complete code is on pastebin. you need to add your path to jquery in the script
A working example is here on jFiddle
The onchange gets called twice: The myOnChange function is called, makes the new input, calls the focus(), the myOnChange gets called again, makes a new input, the 'inner' myOnChange exits and then the 'outer' myOnchange exits.
I'm assuming this is because the focus change fires the onchange()?. I know there is some difference in behaviour between browsers in this.
I would like to stop the .focus() (which seems to be the problem) to NOT call the onchange(), so myOnChange() doesn't get called twice. Anybody know how?
There's a way easier and more reasonable solution. As you expect onchange fire when the input value changes, you can simply explicitly check, if it was actually changed.
function onChangeHandler(e){
if(this.value==this.oldvalue)return; //not changed really
this.oldvalue=this.value;
// .... your stuff
}
A quick fix (untested) should be to defer the call to focus() via
setTimeout(function() { ... }, 0);
until after the event handler has terminated.
However, it is possible to make it work without such a hack; jQuery-free example code:
<head>
<style>
input { display: block; }
</style>
<body>
<div></div>
<script>
var div = document.getElementsByTagName('div')[0];
var field = document.createElement('input');
field.type = 'text';
field.onchange = function() {
// only add a new field on change of last field
if(this.num === div.getElementsByTagName('input').length)
div.appendChild(createField(this.num + 1));
this.nextSibling.focus();
};
function createField(num) {
var clone = field.cloneNode(false);
clone.num = num;
clone.onchange = field.onchange;
return clone;
}
div.appendChild(createField(1));
</script>
I can confirm myOnChange gets called twice on Chrome. But the context argument is the initial input field on both calls.
If you remove the alert call it only fires once. If you are using the alert for testing only then try using console instead (although you need to remove it for testing in IE).
EDIT: It seems that the change event fires twice on the enter key. The following adds a condition to check for the existence of the new field.
function myOnChange(context, curNum) {
nextNum = curNum+1;
if ($('#prefix_'+nextNum).length) return false;// added to avoid duplication
$(context.parentNode).append('<input type="text" onchange="return myOnChange(this,'+nextNum+')" id="prefix_'+nextNum+'" >');
$('#prefix_'+nextNum)[0].focus();
return false;
}
Update:
The $('#prefix_'+nextNum).focus(); does not get called because focus is a method of the dom object, not jQuery. Fixed it with $('#prefix_'+nextNum)[0].focus();.
The problem is indeed that because of the focus(), the onchange is called again. I don't know if this is a good sollution, but this adding this to the function is a quick sollution:
context.onchange = "";
(The onchange is called again, but is now empty. This is also good because this function should never be called twice. There will be some interface changes in the final product that help with problems that would arise from this (mistakes and all), but in the end this is something I probably would have done anyway).
sollution here: http://jsfiddle.net/k4WKH/2/
As #johnhunter says, the focus does not work in the example, but it does in my complete code. I haven't looked into what's going on there, but that seems to be a separate problem.
maybe this some help to anybody, for any reason, in chrome when you attach an event onchage to a input text, when you press the enterkey, the function in the event, do it twice, i solve this problem chaged the event for onkeypress and evaluate the codes, if i have an enter then do the function, cause i only wait for an enterkey user's, that not works for tab key.
input_txt.onkeypress=function(evt){
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
if(charCode === 13) evaluate( n_rows );
};
Try this example:
var curNum = 1;
function myOnChange( context )
{
curNum++;
$('<input type="text" onchange="return myOnChange( this )" id="prefix_'+ curNum +'" >').insertAfter( context );
$('#prefix_'+ curNum ).focus();
return false;
}
jsFiddle.

Categories