keyup not working in IE 8 - javascript

I just realized that this piece of code works well in Firefox but not in IE 8. I need to automatically populate the list when the user enters at least 8 characters in the input field.
$('#inputField').keyup(function (event) {
var $inputField = $(this);
if ($inputField.val().length >= 8) { popularListBox(); }
});
function populateListBox(){
$.get("Default.aspx?name=test", function(data) {
$('#listBox').children().remove();
var options = data;
$("#listBox").html(data);
});
}

You want to detect the change in input field and then do some actions, right?
I think you may detect the changes instead of keyboard actions only. For example, how about if the user paste from clipboard?
Please try these codes:
$('#inputField').bind('propertychange input paste', function() {
// do poppularListBox()
});
It works for most input field including textarea. Please check jQuery site for more information.
In my experience, .keyup() and .keypress() often get errors in IE. I would like to use .keydown() if possible (case by case)

Related

Get input variable after it is filled then do ajax

I have a checkout form where a zipcode is needed. I need this zipcode to get a LocationID. The zipcodes are in 0000XX format but i just need the first 4 digits. Now i have made a (global) javascript to get the locationID trough ajax.
The only problem is that now im using a keyup function that is activated when someone types in a zipcode. But i want it to be activated when a user has typed in something and clicks on another field. how can i do this ?
$('#deliveryzip').bind('keyup change', function(){
//Get zip
var zip = $('#deliveryzip').val();
//Strip first 4 chars from input
//check if 4 chars are integer
//if all ok do ajax...
//Get locationID from zipcode
$.post(jssitebaseUrl+'/ajaxFile.php',{"zip":zip,"action":"getLocInfo"},function(response){
if(response == "ok"){
alert(response);
//If return is ok..
var show = true;
}
});
if(show){
$('#locInfo').show();
} else {
$('#locInfo').hide();
}
return false;
});
Instead of listening to the keyup event, why don't you just listen to the change event?
$('#deliveryzip').on('change', function(){....});
The change event fires when an input field changed and once it looses focus (e.g. through the user clicking on another element). See http://msdn.microsoft.com/en-us/library/ie/ms536912(v=vs.85).aspx for more info (from Microsof) and here the documentation from Mozilla https://developer.mozilla.org/en-US/docs/Web/Reference/Events/change
You can use onBlur function : http://www.w3schools.com/jsref/event_onblur.asp
The onblur event occurs when an object loses focus.
Onblur is most often used with form validation code (e.g. when the user leaves a form field).
Tip: The onblur event is the opposite of the onfocus event.
With jQuery : on( "blur", handler )
Change 'keyup change' to blur
Blur is essentially the opposite of focus
Documentation here

Safari issue with text inputs, text is selected as user enters it causing text to be lost

I have the following input element on my page:
<input class="input" name="custom_fields[new]" placeholder="Enter placeholder" type="text">
I have a Twitter Flight event listener on this element that looks like this:
this.on('keyup', {
inputsSelector: this.updateViewInputs
});
Which triggers this method:
this.updateViewInputs = function(ev) {
var isDeletionKeycode = (ev.keyCode == 8 || ev.keyCode == 46);
// Remove field is user is trying to delete it
if (isDeletionKeycode && this.shouldDeleteInput(ev.target.value, this.select('inputsSelector').length)) {
$(ev.target.parentNode).remove();
}
// Add another field dynamically
if (this.select('lastInputsSelector')[0] && (ev.target == this.select('lastInputSelector')[0]) && !isDeletionKeycode) {
this.select('inputsContainer').append(InputTemplate());
}
// Render fields
that.trigger('uiUpdateInputs', {
inputs: that.collectInputs()
});
}
And finally triggers uiUpdateInputs:
this.after('initialize', function() {
this.on(document, 'uiUpdateInputs', this.updateInputs)
});
this.updateInputs = function(ev, data) {
// Render all inputs provided by user
this.select('inputListSelector').html(InputsTemplate({ inputs: data.inputs }));
}
All of this functionality works as expected on Chrome and Firefox. Users can type into the input and see the page change in 'real time'. Users also get additional fields that they can enter text into and see the page change.
The issue in question arises when using Safari, as a user enters text into the described input field the text in the input field becomes highlighted (selected) and when they enter the next character all the content is replaced with that single character. This results in the user not being able to enter more than 1 or 2 characters before having them all replaced by the next entered character.
I have tried several approaches to fix this problem but none have worked, they include:
Using a setTimeout to delay the code run on the keyup event
Using Selection to try to disable the selection of the text using collapseToEnd.
Using click,focus,blur events to try to remove the selection from the entered text
Triggering a right arrow key event to try to simply move the cursor forward so they user does not delete the selected text
Using setInterval to routinely remove selections made by the window
I am very confused why this is happening and I am wondering if this is a bug in webkit with Flight. I see no issue with the Firefox or Chrome versions of this page. Thanks for any help!
This seems to be an issue with certain versions of Safari. When listening for the keyup function in javascript it will automatically select all of the text in the box and subsequently delete it all when the next key is typed. To prevent this from happening call preventDefault on the event object that is passed to the keyup function.
this.on('keyup', function(e) {
e.preventDefault()
});

jQuery Searchbox IE9 issue

I'm working on an issue here that only occurs in IE8/9
We have 2 search boxes. One in the header that uses jQuery's Autocomplete, and the other which is specifically for an archiving feature we have on certain pages. What should happen is if the Autocomplete searchbox is in focus and we hit Enter after typing something in, it searches with that value. Easy enough.
However, in IE8/9, no matter which text box has focus, the Enter key will trigger that event.
Here's what we've got:
jQuery(".autocomplete").keydown(function(event) {
if (jQuery(".autocomplete").is(":focus")){
var query;
if (event.which === 13) {
event.preventDefault();
query = this.value;
return window.location.href = "/search?q=" + query;
}
}
});
I've also tried .keypress() and it yields the same result. We're using jQuery 2.0.0
Our team is relatively new to jQuery, so we're probably just doing this wrong.
It should only be firing on searchboxes with the .autocomplete class, and only if that particular box has focus.
Thanks!
I apologize, apparently a different team had added a .js file that was interfering with the operation of this jquery script in our file.

Any event triggered on autocomplete?

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.

Do not allow Paste any non alphanumeric characters

I don’t want user to allow pasting of any non Alphanumeric characters on a text box.
How do I restrict this in Javascript?
Thanks!!
Using jQuery, this is one way to do it:
HTML:
​<form name='theform' id='theform' action=''>
<textarea id='nonumbers' cols='60' rows='10'> </textarea>
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
JavaScript:
$().ready(function(){
$("textarea#nonumbers").keyup(removeextra).blur(removeextra);
});
function removeextra() {
var initVal = $(this).val();
outputVal = initVal.replace(/[^0-9a-zA-Z]/g,"");
if (initVal != outputVal) {
$(this).val(outputVal);
}
};
Try it out here.
EDIT: As remarked in the comments, the original (using the .keyup() event) would have left open the possibility of pasting via the mouse context menu, so I've added a .blur() event. .change() would have been possible too, but there are reports of bugginess. Another option is using .focusout(). Time to experiment...
You can use the onblur event of text box.
function remove()
{
var otxt=document.getElementById('txt1');
var val=otxt.value;
for(i=0;i<val.length;i++)
{
var code=val.charCodeAt(i);
if(!(code>=65 && code<=91) && !(code >=97 && code<=121) && !(code>=48 && code<=57))
{ otxt.value=""; return ; }
}
}
<input type="text" id="txt1" onblur="remove();" />
It will remove all value of text box when you input non alphanumeric value.
Why has no one suggested using the OnPaste event? That is fully supported in IE, Safari and Chrome.
Docs for using OnPaste in IE
Docs for using OnPaste in Webkit
In JQuery, that would look like this:
$(input).bind("paste", function(e){ RemoveNonAlphaNumeric(); })
That covers 75% of the browser market.
If you use JQuery, OnPaste is automatically normalized in Firefox so that it works there too. If you can't use JQuery, there is an OnInput event that works.
The working solution is to use a fast setTimeout value to allow the input's value property to be filled.
Basically like this:
$("input").bind("paste", function(e){RemoveAlphaChars(this, e);});
function RemoveAlphaChars(txt, e)
{
setTimeout(function()
{
var initVal = $(txt).val();
outputVal = initVal.replace(/[^0-9]/g,"");
if (initVal != outputVal)
$(txt).val(outputVal);
},1);
}
I have tested this in IE, Chrome and Firefox and it works well. The timeout is so fast, you can't even see the characters that are being removed.
I'm not sure how you can prevent pasting, but you can filter the contents either on the submit or on the change event.
It's better to validate form - check this great jQuery's plugin - http://docs.jquery.com/Plugins/Validation/ and you can use the "number" rule : http://docs.jquery.com/Plugins/Validation/Methods/number. Really simple and easy to tune thing!
Assuming:
<textarea id="t1"/>
You could modify the onchange event handler for the textarea to strip out anything not alphanumeric:
document.getElementById('t1').onchange = function () {
this.value = this.value.replace(/\W/,'');
}

Categories