I am using EasyAutocomplete, it works well, only problem I am facing - Input box loses control when EasyAutocomplete is attached to it.
I want EasyAutocomplete to get activated after the user has typed 2 characters.
When I type 1 character nothing happens as needed, but after 2nd character has been typed EasyAutocomplete must get attached and should start working. However, what happens is I have to click outside of the input box to make things happen.
It is just this 'outside click', that I have to do to make this plugin work, is problematic for me.
I have tried input event as well but i did not work as required.
The change event seems quite suited for my requirement.
How do I solve this issue?
var ib = $("#inputbox");
$(document).on("keyup", ib,function(e) {
leng = ib.val();
});
$(document).on("change", ib,function(e) {
if(leng.length < 2){
#do something
}else{
ib.easyAutocomplete(options);
}
});
First you should change "change" by "keyup"
Second leng doesn't update as you put it outside of the event
Lastly an event on document may not be the best if you want this event to trigger only on this element, change document by your element
$("#inputbox").on("keyup", ib,function(e) {
if($("#inputbox").val().length < 2){
#do something
}else{
ib.easyAutocomplete(options);
}
});
Related
Right now I have this:
Event.observe(
'hidden',
'keydown',
itemOptions["_something"].showButtonsForThat
);
whereas showButtonsForThat is showButtonsForThat : function(){....function body....}.
But I needed to add other event handlers:
Event.observe(
'inputF',
'keydown',
function() { document.getElementById('hidden').value = document.getElementById('inputF').value; }
);
Event.observe(
'inputF',
'blur',
function() { document.getElementById('hidden').value = document.getElementById('inputF').value; }
);
which will change the value of the hidden field every time I change something in the input field. And now I want the first event handler (about the hidden element) to trigger whenever its value is changed (which changes according to whatever is in the input field..
I tried with eventName 'change' but unsuccessful. Somehow using onchange="myFoo();" in the html element + jQuery, etc., didn't work. Maybe my syntax misplacement mistake, but I tried many things and following different examples.
Clarification: I want to observe the change of hidden, because it will change automatically when I type something different in inputF. So I basically will NOT interact with hidden at all.
If none of the traditional ways worked for you, you could simply use a work-around, as bellow:
Event.observe(
'inputF',
'keyup',
itemOptions["_something"].showButtonsForThat
);
This means that you will still observe the inputF field, but will call your needed function on that. Anyway, you will call the handler on change of hidden, which on the other hand changes along with inputF, meaning that changing either of the fields happens at the same time and for the same purpose.
P.S. Better use keyup event name (as in my example), because keydown requires one more click, for the last symbol to be updated. I.e., if you type asde in inputF, then you will have asd in hidden, unless you click once more with the keyboard. And with keyup you won't have this problem.
var h = document.getElementById('hidden'),
f = function() { h.value = this.value; };
Event.observe('inputF','keydown', f);
Event.observe('inputF','blur', f);
...
I don't usually like to bother you all but I'm stuck on something and I can't find an answer anywhere, hope you guys can help me out!
I'm building a web app and designing it so the interface matches iOS7.
http://danj.eu/webdesign/new
I've got an input form, and I need the button to submit the form to only turn blue and become selectable once the validation has completed. I've wrote some JS to validate the input but this only runs once! I need to run the function every time the user modifies the value of the input.
This is what I've got so far for the JS:
function validateInput(){
if (document.getElementById('projectname').value.length < 2)
document.getElementById('forwardbutton').style.color = "#c4c4c5";
else
document.getElementById('forwardbutton').style.color = "#0e81ff";
}
Thanks guys!
add to your input onchange listener:
var input = document.getElementById("myInput");
input.addEventListener('change', validateInput, false);
this will fire validateInput function every time the value changes.
PS. you should cache your DOM elements that you get in your validation function, because it's searching through the DOM to find them always when function is fired- this can be heavy in a big DOM tree
jsFiddle Demo
You can bind to the input event using jquery which handles virtually all input events simultaneously
<input id="myInput" type="text" />
<div id="output"></div>
js
$('#myInput').bind('input',function(){
if( this.value.length < 2 ){
document.getElementById('output').style.color = "#c4c4c5";
}else{
document.getElementById('output').style.color = "#0e81ff";
}
$('#output').html(this.value);
});
I do not know if you are opposed to jQuery, but I'll provide the jQuery way of doing this. It's very simple with jQuery. You'd use a keyboard event handler, specifically the Key Up event handler.
In your event handler, you'd then check the length of the field and based on the length you would set the enabled or disabled state of the button.
$('#input-element').keyup(function () {
if (document.getElementById('projectname').value.length < 2)
document.getElementById('forwardbutton').style.color = "#c4c4c5";
else
document.getElementById('forwardbutton').style.color = "#0e81ff";
}
});
You can also use jQuery to set the color or enabled state as well, instead of your previous code. Up to you.
Do you mean
function validateInput(){
if (document.getElementById('projectname').value.length < 2)
document.getElementById('forwardbutton').style.color = "#c4c4c5";
else
document.getElementById('forwardbutton').style.color = "#0e81ff";
}
and then perhaps this?
document.getElementById('projectname').onchange=validateInput;
More information would be helpful.
This seems like a simple thing but google hasn't turned up anything for me:
How can I bind to a text / value change event only, excluding an input gaining focus? Ie, given the following:
$(function(){
$('input#target').on('keyup', function(){
alert('Typed something in the input.');
});
});
...the alert would be triggered when the user tabs in and out of an element, whether they actually input text or not. How can you allow a user to keyboard navigate through the form without triggering the event unless they input/change the text in the text field?
Note: I'm showing a simplified version of a script, the reason for not using the change event is that in my real code I have a delay timer so that the event happens after the user stops typing for a second, without them having to change focus to trigger the event.
Store the value, and on any key event check if it's changed, like so:
$(function(){
$('input#target').on('keyup', function(){
if ($(this).data('val')!=this.value) {
alert('Typed something in the input.');
}
$(this).data('val', this.value);
});
});
FIDDLE
Simply use the .change event.
Update: If you want live change notifications then do you have to go through the keyup event, which means that you need to program your handler to ignore those keys that will not result in the value being modified.
You can implement this with a whitelist of key codes that are ignored, but it could get ugly: pressing Del results in the value being changed, unless the cursor is positioned at the end of the input in which case it does not, unless there happens to be a selected range in the input in which case it does.
Another way which I personally find more sane if not as "pure" is to program your handler to remember the old value of the element and only react if it has changed.
$(function() {
// for each input element we are interested in
$("input").each(function () {
// set a property on the element to remember the old value,
// which is initially unknown
this.oldValue = null;
}).focus(function() {
// this condition is true just once, at the time we
// initialize oldValue to start tracking changes
if (this.oldValue === null) {
this.oldValue = this.value;
}
}).keyup(function() {
// if no change, nothing to do
if (this.oldValue == this.value) {
return;
}
// update the cached old value and do your stuff
this.oldValue = this.value;
alert("value changed on " + this.className);
});
});
If you do not want to set properties directly on the DOM element (really, there's nothing wrong with it) then you could substitute $(this).data("oldValue") for this.oldValue whenever it appears. This will technically have the drawback of making the code slower, but I don't believe anyone will notice.
See it in action.
This will do it, set a custom attribute and check against that:
$('input').focus(function(){
$(this).attr('originalvalue',$(this).val());
});
$('input').on('keyup',function(){
if($(this).val()===$(this).attr('originalvalue')) return;
alert('he must\'ve typed something.');
});
Be wary of events firing multiple times.
Here is another version that plainly tests if the input field is empty.
If the input is empty then the action is not performed.
$(function(){
$(selector).on('keyup', function(){
if ($(this).val()!='') {
alert('char was entered');
}
})
});
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/
I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the keyup, change and click events.
The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither change nor click). Note that if you select from the autocomplete box and the blur the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .
See: http://jsfiddle.net/pYKKp/ (hopefully you have filled out a lot of forms in the past with an input named "email").
HTML:
<input name="email" />
<div id="whatever"><whatever></div>
CSS:
div {
float: right;
}
Script:
$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
I recommending using monitorEvents. It's a function provide by the javascript console in both web inspector and firebug that prints out all events that are generated by an element. Here's an example of how you'd use it:
monitorEvents($("input")[0]);
In your case, both Firefox and Opera generate an input event when the user selects an item from the autocomplete drop down. In IE7-8 a change event is produced after the user changes focus. The latest Chrome does generate a similar event.
A detailed browser compatibility chart can be found here:
https://developer.mozilla.org/en-US/docs/Web/Events/input
Here is an awesome solution.
$('html').bind('input', function() {
alert('test');
});
I tested with Chrome and Firefox and it will also work for other browsers.
I have tried a lot of events with many elements but only this is triggered when you select from autocomplete.
Hope it will save some one's time.
Add "blur". works in all browsers!
$("input").on('blur keyup change click', function () {
As Xavi explained, there's no a solution 100% cross-browser for that, so I created a trick on my own for that (5 steps to go on):
1. I need a couple of new arrays:
window.timeouts = new Array();
window.memo_values = new Array();
2. on focus on the input text I want to trigger (in your case "email", in my example "name") I set an Interval, for example using jQuery (not needed thought):
jQuery('#name').focus(function ()
{
var id = jQuery(this).attr('id');
window.timeouts[id] = setInterval('onChangeValue.call(document.getElementById("'+ id +'"), doSomething)', 500);
});
3. on blur I remove the interval: (always using jQuery not needed thought), and I verify if the value changed
jQuery('#name').blur(function ()
{
var id = jQuery(this).attr('id');
onChangeValue.call(document.getElementById(id), doSomething);
clearInterval(window.timeouts[id]);
delete window.timeouts[id];
});
4. Now, the main function which check changes is the following
function onChangeValue(callback)
{
if (window.memo_values[this.id] != this.value)
{
window.memo_values[this.id] = this.value;
if (callback instanceof Function)
{
callback.call(this);
}
else
{
eval( callback );
}
}
}
Important note: you can use "this" inside the above function, referring to your triggered input HTML element. An id must be specified in order to that function to work, and you can pass a function, or a function name or a string of command as a callback.
5. Finally you can do something when the input value is changed, even when a value is selected from a autocomplete dropdown list
function doSomething()
{
alert('got you! '+this.value);
}
Important note: again you use "this" inside the above function referring to the your triggered input HTML element.
WORKING FIDDLE!!!
I know it sounds complicated, but it isn't.
I prepared a working fiddle for you, the input to change is named "name" so if you ever entered your name in an online form you might have an autocomplete dropdown list of your browser to test.
Detecting autocomplete on form input with jQuery OR JAVASCRIPT
Using: Event input. To select (input or textarea) value suggestions
FOR EXAMPLE FOR JQUERY:
$(input).on('input', function() {
alert("Number selected ");
});
FOR EXAMPLE FOR JAVASCRIPT:
<input type="text" onInput="affiche(document.getElementById('something').text)" name="Somthing" />
This start ajax query ...
The only sure way is to use an interval.
Luca's answer is too complicated for me, so I created my own short version which hopefully will help someone (maybe even me from the future):
$input.on( 'focus', function(){
var intervalDuration = 1000, // ms
interval = setInterval( function(){
// do your tests here
// ..................
// when element loses focus, we stop checking:
if( ! $input.is( ':focus' ) ) clearInterval( interval );
}, intervalDuration );
} );
Tested on Chrome, Mozilla and even IE.
I've realised via monitorEvents that at least in Chrome the keyup event is fired before the autocomplete input event. On a normal keyboard input the sequence is keydown input keyup, so after the input.
What i did is then:
let myFun = ()=>{ ..do Something };
input.addEventListener('change', myFun );
//fallback in case change is not fired on autocomplete
let _k = null;
input.addEventListener( 'keydown', (e)=>_k=e.type );
input.addEventListener( 'keyup', (e)=>_k=e.type );
input.addEventListener( 'input', (e)=>{ if(_k === 'keyup') myFun();})
Needs to be checked with other browser, but that might be a way without intervals.
I don't think you need an event for this: this happens only once, and there is no good browser-wide support for this, as shown by #xavi 's answer.
Just add a function after loading the body that checks the fields once for any changes in the default value, or if it's just a matter of copying a certain value to another place, just copy it to make sure it is initialized properly.