JS onkeydown/onkeyup - convert to jQuery keydown/keyup - javascript

I currently have some js for phone number validation that is using inline event listeners in the input field. I need to change this example so that instead of attaching the event listeners inline, I would be targeting the DOM element in jQuery and adding the event listeners. Here's a working example of what I have so far: http://jsfiddle.net/yVdgL/21/
window.mask = function (e,f){
var len = f.value.length;
var key = whichKey(e);
if((key>=47 && key<=58) || (key>=96 && key<=105))
{
if( len==1 )f.value='('+f.value
else if(len==4 )f.value=f.value+')'
else if(len==8 )f.value=f.value+'-'
else f.value=f.value;
}
}
function whichKey(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
return code
}
and
<input type="text" name="phone" id="phone" onkeydown="mask(event,this)" onkeyup="mask(event,this)" maxlength="13" />
I tried this but was unable to achieve the functionality that I need.

i have update you jsfiddle example:-
jQuery(document).ready(function(){
jQuery('#edit-phone1').keyup(function(event){
mask(event,this);
});
jQuery('#edit-phone1').keydown(function(event){
mask(event,this);
});
});
click here to see working example:-
http://jsfiddle.net/yVdgL/38/
or you can try :-
$(document).ready(function() {
$('#edit-phone1').on("keyup keydown", function(e) {
mask(e, this);
});
});
link for this is:-http://jsfiddle.net/yVdgL/56/

In older, pre-HTML5 browsers, $("#phone").keyup( function ) or keydown is definitely what you're looking for.
In HTML5 there is a new event, "input", which behaves exactly like you seem to think "change" should have behaved - in that it fires as soon as a key is pressed to enter information into a form. $("#phone").bind('input',function);

You never defined event.
jQuery('#edit-phone1').keyup(function(){
jQuery('#edit-phone1').mask(event,this); //<-- what is event?
});
just add it
Second issue is you are treating window.mask like a jQuery plugin and it is not a plugin.
jQuery('#edit-phone1').keyup(function(event){ //<-- add event here
mask(event,this);
});

Related

javascript not working on phone [duplicate]

I have created a simple code to handle keypress event:
var counter = 0;
$('input').on('keypress', function () {
$('div').text('key pressed ' + ++counter);
});
JSFiddle.
But keypress event handler is not raised on mobile browser (Android 4+, WindowsPhone 7.5+).
What could be the issue?
I believe keypress is deprecated now. You can check in the Dom Level 3 Spec. Using keydown or keyup should work. The spec also recommends that you should use beforeinput instead of keypress but I'm not sure what the support of this is.
Use the keyup event:
// JavaScript:
var counter = 0;
document.querySelector('input').addEventListener('keyup', function () {
document.querySelector('div').textContent = `key up ${++counter}`;
});
// jQuery:
var counter = 0;
$('input').on('keyup', function () {
$('div').text('key up ' + ++counter);
});
Use jQuery's input event, like this:
$( 'input' ).on( 'input', function() {
...
} );
With this you can't use e.which for determining which key was pressed, but I found a nice workaround here: http://jsfiddle.net/zminic/8Lmay/
$(document).ready(function() {
var pattForZip = /[0-9]/;
$('#id').on('keypress input', function(event) {
if(event.type == "keypress") {
if(pattForZip.test(event.key)) {
return true;
}
return false;
}
if(event.type == 'input') {
var bufferValue = $(this).val().replace(/\D/g,'');
$(this).val(bufferValue);
}
})
})
Yes, some android browser are not supporting keypress event, we need use to only keydown or keyup but will get different keycodes, to avoiding different key codes use the following function to get the keycode by sending char value.
Eg:
function getKeyCode(str) {
return str && str.charCodeAt(0);
}
function keyUp(){
var keyCode = getKeyCode("1");
}
I think it is bad idea to use other events in place of 'keypress'.
What you need to do is just include a jQuery file into your project.
A file named jQuery.mobile.js or quite similar (ex. jQuery.ui.js) of any version can help you.
You can download it from : https://jquerymobile.com/download/

jQuery - triggering multiple events one by one

I'm using jquery tagsInput plugin where I need to dynamically modify the query(deleting the query or entering the new query) without actually typing in the search box connected with tagsInput plugin.
My problem here is I want to trigger backspace event at first then enter event next. Here is the code.
function triggering_events() {
$(".tag").each(function() {
var e = jQuery.Event("keydown");
e.keyCode = 8;
e.which = 8;
$("#input-search_tag").trigger(e); //triggering backspace event
});
var input = $("#input-search_tag");
input.val("food");
input.trigger(e); //triggering enter event
}
But only the backspace event is triggering from the above code. How can I make that enter event work?
Could anyone point out the mistake I've done?
Thanks!
you can try use the methods removeTag and addTag for remove and add tag's:
function triggering_events() {
var
idInput = 'input-search',
input = $("#" + idInput);
$("#"+idInput+"_tagsinput .tag").each(function() {
var tag = $.trim($(this).find('span:eq(0)').text());
input.removeTag(tag);
});
input.addTag("food");
}
run
There is an issue here:
$("#input-search_tag").val("food").trigger(e); //triggering enter event
.val() returns you a string value of the jquery Element, it is not a chainable method. strings do not have a trigger method.
You could fix this by splitting it into two calls:
var input = $("#input-search_tag");
input.val("food");
input.trigger(e); // triggering enter event
Or using .end():
$("#input-search_tag").val("food").end().trigger(e); //triggering enter event
Edit: putting it all together, along with reusing one event instead of creating multiples:
function triggering_events() {
var e = jQuery.Event("keydown");
e.which = 8;
$(".tag").each(function() {
$("#input-search_tag").trigger(e); // triggering backspace event
});
e.which = 13;
$("#input-search_tag").val("food").end().trigger(e); // triggering enter event
}

Observer events in JS Prototype - two events at the same time

I have an input box that takes a number that gets verified in function opConfig.reloadPrice(). I set 2 observers one the same element, on 'change' it executes the code when I click outside the box or use tab-if the change has been made. On 'keypress' it checks if the return key was pressed then executes the code AND it also triggers the 'change' observer!! So in this case the function opConfig.reloadPrice() gets executed twice (and I end up with two identical alert boxes).
The code that I have now:
<input type="text" value="" name="options[1]" id="options_1" onkeypress="return disableEnterKey(event)">
Event.observe($('options_1'), 'change', function(e){
opConfig.reloadPrice();
});
Event.observe($('options_1'),'keypress', function(e){
if (e.keyCode == Event.KEY_RETURN)
opConfig.reloadPrice();
});
I've tried several different solutions (I've tried 'blur' event, putting one observer in the other... )
I'm looking for a solution similar to this one
jQuery-Two events at the same time
Thanks a million
EDIT-Solved:
Thanks to katspaugh I solved this. There were few things that were not clear to me, one of them is: 'keypress' event is observed before 'change' event, which is why you can set variables in one observer and check them later in another (this is also why it took me a while to understand katspaughs code :-) ).
Anyway, I change the code a bit that it suits me:
var enterPressed = 0;
Event.observe($('options_1'), 'change', function(){
if (enterPressed !== 1) {
opConfig.reloadPrice();
}
enterPressed = 0;
});
Event.observe($('options_1'), 'keypress', function(e){
if ((e.keyCode == Event.KEY_RETURN) || (e.keyCode == Event.KEY_TAB)) {
enterPressed = 1;
opConfig.reloadPrice();
}
else
enterPressed = 0;
});
Cheers,
jazkat
Save the current value of the input field in an upper-scope variable (up-value).
If the value changes in one of the events, fire the handler and update the upvalue:
var oldVal;
$('options_1').observe(
'change', function () {
var val = this.value;
if (oldVal !== val) {
oldVal = val;
opConfig.reloadPrice();
}
}
).observe(
'keypress', function(e) {
oldVal = this.value;
if (e.keyCode == Event.KEY_RETURN) {
opConfig.reloadPrice();
}
}
);
Also, you'd better remove the inline listener in HTML (and never add them again):
<input type="text" name="options[1]" id="options_1" />
Demo.

Bind enter key to specific button on page

<input type="button" id="save_post" class="button" value="Post" style="cursor:pointer;"/>
How can I bind the enter key on the persons keyboard to this specific button on the page? It's not in a form, and nor do I want it to be.
Thanks!
This will click the button regardless of where the "Enter" happens on the page:
$(document).keypress(function(e){
if (e.which == 13){
$("#save_post").click();
}
});
If you want to use pure javascript :
document.onkeydown = function (e) {
e = e || window.event;
switch (e.which || e.keyCode) {
case 13 : //Your Code Here (13 is ascii code for 'ENTER')
break;
}
}
using jQuery :
$('body').on('keypress', 'input', function(args) {
if (args.keyCode == 13) {
$("#save_post").click();
return false;
}
});
Or to bind specific inputs to different buttons you can use selectors
$('body').on('keypress', '#MyInputId', function(args) {
if (args.keyCode == 13) {
$('#MyButtonId').click();
return false;
}
});
Vanilla JS version with listener:
window.addEventListener('keyup', function(event) {
if (event.keyCode === 13) {
alert('enter was pressed!');
}
});
Also don't forget to remove event listener, if this code is shared between the pages.
Maybe not quite what you're looking for but there is a HTML property that lets you assign a specific button called an access key to focus or trigger an element. It's like this:
<a href='https://www.google.com' accesskey='h'>
This can be done with most elements.
Here's the catch: it doesn't always work. for IE and chrome, you need to be holding alt as well. On firefox, you need to be holding alt and shift (and control if on mac). For safari, you need to be holding control and alt. On opera 15+ you need alt, before 12.1 you need shift and esc.
Source: W3Schools

How to disable Paste (Ctrl+V) with jQuery?

How can I disable Paste (Ctrl+V) option using jQuery in one of my input text fields?
This now works for IE FF Chrome properly... I have not tested for other browsers though
$(document).ready(function(){
$('#txtInput').on("cut copy paste",function(e) {
e.preventDefault();
});
});
Edit: As pointed out by webeno, .bind() is deprecated hence it is recommended to use .on() instead.
Edit: It's almost 6 years later, looking at this now I wouldn't recommend this solution. The accepted answer is definitely much better. Go with that!
This seems to work.
You can listen to keyboard events with jQuery and prevent the event from completing if its the key combo you are looking for.
Note, check 118 and 86 (V and v)
Working example here:
http://jsfiddle.net/dannylane/9pRsx/4/
$(document).ready(function(){
$(document).keydown(function(event) {
if (event.ctrlKey==true && (event.which == '118' || event.which == '86')) {
alert('thou. shalt. not. PASTE!');
event.preventDefault();
}
});
});
Update:
keypress doesn't fire in IE, use keydown instead.
As of JQuery 1.7 you might want to use the on method instead
$(function(){
$(document).on("cut copy paste","#txtInput",function(e) {
e.preventDefault();
});
});
jQuery('input.disablePaste').keydown(function(event) {
var forbiddenKeys = new Array('c', 'x', 'v');
var keyCode = (event.keyCode) ? event.keyCode : event.which;
var isCtrl;
isCtrl = event.ctrlKey
if (isCtrl) {
for (i = 0; i < forbiddenKeys.length; i++) {
if (forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
return false;
}
}
}
return true;
});
I tried this in my Angular project and it worked fine without jQuery.
<input type='text' ng-paste='preventPaste($event)'>
And in script part:
$scope.preventPaste = function(e){
e.preventDefault();
return false;
};
In non angular project, use 'onPaste' instead of 'ng-paste' and 'event' instesd of '$event'.
The following code will disable cut, copy and paste from full page.
$(document).ready(function () {
$('body').bind('cut copy paste', function (e) {
e.preventDefault();
});
});
The full tutorial and working demo can be found from here - Disable cut, copy and paste using jQuery
$(document).ready(function(){
$('#txtInput').on("cut copy paste",function(e) {
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtInput" />
You can catch key event :
function checkEventObj ( _event_ ){
// --- IE explorer
if ( window.event )
return window.event;
// --- Netscape and other explorers
else
return _event_;
}
document.keydown = function(_event) {
var e = checkEventObject(_event);
if( e.ctrlKey && (e.keyCode == 86) )
window.clipboardData.clearData();
}
Not tested but, could help.
Source from comentcamarche and Zakaria
$(document).ready(function(){
$('#txtInput').live("cut copy paste",function(e) {
e.preventDefault();
});
});
On textbox live event cut, copy, paste event is prevented and it works well.
I have tested the issue on chrome browser and it is working for me.Below is a solution for preventing the paste code in your textbox and also prevent the right click.
$(".element-container").find('input[type="text"]').live("contextmenu paste", function (e) {
e.preventDefault();
});
$(document).ready(function(){
$('input').on("cut copy paste",function(e) {
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

Categories