No alert when input is entered - javascript

I am trying to get it so that when I press enter while focused on an input, it alerts something.
I have an input tag,
<input></input>
Then I have javascript,
document.getElementsByTagName("input").keyup = function(e) {
if (e.keyCode == 13) {
alert("1111");
}
};
Why is this not working? Here is my codepen: http://codepen.io/darkfyi/pen/meBdzZ.

There are two problems with your code:
The document.getElementsByTagName method returns a HTMLCollection, so you must iterate through this collection, or use the first item by using [0].
If you want to delegate the event keyup by its property, you should use .onkeyup = function() {, as there is no HTMLInputElement.keyup method. You would use keyup in addEventListener method, for example.
So, your code should be something like:
document.getElementsByTagName("input")[0].onkeyup = function(e) {
if (e.keyCode == 13) {
alert("1111");
}
};
Updated codepen.

Related

jQuery to prevent user from inputting if regular expression is not matched by using preventdefault

Every time user enter, value is checked with regular expression, I'm trying to restrict user from entering further into input field if regexp is not matched
Using keyup event, preventdefault never fires and using keypress event, user is unable to input at all because in the begining, value in input field shows as "" (nothing)
var discountRegex = /(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/
$("#" + (idOfElement)).on("keyup",function (e) {
var val=this.value
var k = e.keyCode
if(k==46 ||(k > 48 && k <97)){
console.log(k)
return discountRegex.test(val);
}
});
in the above code idOfElement is the id i get on whichever field i focus.
Please refer sample code. If input key is invalid input will not accept it. Also please find fiddle for same in comment.
<input type="text">
$(document).ready(function(){
$("input").bind('keypress', function(e) {
var str = e.keyCode;
if (/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/.test(str)) {
alert('Invalid')
e.preventDefault();
} else {
alert('Valid');
}
});
});
You can check if the regex is matched and if not you can remove the last char like the example below
I updated the code with keydown example
Example

Using .keydown() to return div id?

I'm not really sure if I'm phrasing this correctly, but what I'm trying to do is have a function return a div's id on a keydown event.
Say my HTML is:
<div class="pad" id="snare" data-key="97"></div>
<div class="pad" id="kick" data-key="98"></div>
Essentially I want my JS to do something like this:
function handlekeydown(e) {
console.log("data-key: " + e.keyCode);
if (e.keycode == $(".pad").data("key")) {
return this.id
}
}
I could write a switch statement with each keycode returning a variable with the same name as the id, but that would defeat the purpose of having it in my HTML.
How would I write a function to search a div for a data-key that would match the keycode and then return its id?
As per the question
How would I write a function to search a div for a data-key that would match the keycode?
You can do it by:
function handlekeydown(e) {
var id;
var element = $('[data-key="' + e.keyCode + '"]');
if (element.length) {
id = element[0].id;
}
}
But as mentioned above you can't return the id from the handler, you might wanna call a method from the event handler which uses id.
function processId(id) {
console.log(id);
}
function handlekeydown(e) {
var element = $('[data-key="' + e.keyCode + '"]');
if (element.length) {
processId(element[0].id);
}
}
A keydown event is a keyboard event.
A keydown event will only trigger on the currently activeElement of the document.
You need a completely different approach - on which I will come forth with a solution proposal if you decide to change your current approach with something that might actually work for a change.
p.s.: I will update this same reply.

How to Exclude Child Element from jQuery Event Handler?

I am modifying an existing web page. I added a <textarea> to the page, but found that the Enter key doesn't work as expected.
After spending considerable time searching, I found the following:
$('form').keypress(function (e) {
if (e.keyCode == 13)
return false;
});
I need to leave as much as much of the existing functionality in place as I can. But I need to disable this for my <textarea>. (It appears mine is the only <textarea> on the page.
But how can I do this? I thought about adding .not('textarea') to the selector above. But that doesn't work because the handler is on the form, which is not a textarea.
I can I exclude <textarea>s from the filter above?
jsBin demo
You can simply target the inputs
$('form input').keypress(function (e) {
if (e.which == 13) e.preventDefault(); // Don't misuse return false
});
the textarea will go on with the enter key as usual
Depends on the use-case.
If you want to be sure nothing brakes use:
$('form *:not(textarea)').keypress(function (e) {
if (e.which == 13) e.preventDefault();
});
where * targets every children, and :not selector excludes the desired one.
here's another example:
$('form *').keypress(function (e) {
if (e.which == 13 && this.tagName!=="TEXTAREA") e.preventDefault();
});
You can check the if the target is the textarea :
$('form').keypress(function (e) {
if($(e.target).is('textarea')) return;
if (e.keyCode == 13)
return false;
});
Add a filter inside your function like this
$('form').keypress(function (e) {
if (e.keyCode == 13 || e.target.tagName.toLowerCase() == 'textarea')
return false;
});
the simplest way is to use on(), so you don't need to do any extra element comparing inside the event handler:
$('form').on("keypress", ":not(textarea)", function (e) {
if (e.keyCode == 13)
return false;
});
you use on() to watch the form, and the css selector to avoid textareas.
to easily tweak later, you can blacklist other elements by tagname or class using more :not() operators sperated by commas. plus, on() is now recommended over the older single-purpose handlers anyway.

Alert when backspace is pressed inside textbox

I have a grid with three read-only columns. Whenever user goes in there and try to edit by pressing backspace, I need to alert by giving a message. I am using this script and it doesn't work? Can anyone correct me?
$(document).ready(function () {
$('#txtCode').bind('keypress', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}
});
instead of keypress try with keyup or keydown with .on() method:
$('#txtCode').on('keyup keydown', function (e) {
You can bind multiple events like this too.
and one more thing closing of $('#txtCode') seems to be missing });
$(document).ready(function () {
$('#txtCode').on('keyup keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}); //<----");" this is the closing you misssed this
});
See the fiddle in action
If this is all the code you are testing, you weren't closing the function properly, annotated in my posted code. Also use keyup instead of keypress
$(document).ready(function () {
$('#txtCode').bind('keyup', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}); /*<-- You weren't closing your function properly*/
});
Fiddle
You do indeed need to add a return false statement to ensure the character doesn't get deleted anyway. I also took it a step further and extended jQuery with a preventKeyUsage method.
$(document).ready(function () {
$.fn.preventKeyUsage = function (key, message) {
return this.each(function () {
$(this).on('keydown', function (e) {
return (e.keyCode === key) ? (function () {
alert(message);
return false;
})() : true;
});
});
};
$('#txtCode').preventKeyUsage(8, 'The column is read-only and is not editable');
});
New Fiddle
Working code is:
Java Script Code:
$(document).ready(function () {
$('#txtCode').bind('keypress keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
Here is the updated code
<input type="text" id="txtCode" />
$(document).ready(function () {
$('#txtCode').bind('keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
return false;
}
});
});
Fiddle Demo
Try this
$(document).ready(function () {
$('#txtCode').on('keyup', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
DEMO (Working on Firefox & Chrome)
$('#textbox').keydown(function(event){
if(event.keyCode == 8){
alert("Backspace not allowed..");
return false;
}
});
http://jsfiddle.net/xF9jL/1/
You are missing }); of keypress. google chrome have issues with keypress, u can try keydown instead
$(document).ready(function () {
$('#txtCode').bind('keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
To use delete ,arrows, backspace keys in Chrome you must use keydown. keypress on these keys work only in Firefox and Opera.
DEMO
You can probably solve the underlying issue by either not using an element that accepts input, or by using the disabled attribute:
<textarea name="example" disabled>Some text</textarea>
If you are posting back to the sever, you should assume the user has edited the field, no matter what you do to prevent it.
keypress event won't give keycodes for all keys in all browsers . Better use keyup or keydown event which gives keycode for all keys in all browsers
In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

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

Categories