Allow "Enter" key working but not breaking line given - javascript

Hi i need to achieve that breakline works here, because you can type enter, but after you type again no breaking line is given.
i make this fiddle http://jsfiddle.net/FPN9w/
Here is the JS code.
$(function () {
//you have to escaped the - character in a character class
var cleanRx = /[^a-zA-Z0-9 áéíóúÁÉÍÓÚÜüñѨ´,.¿?%&$!¡ªº#"()\-_\/]/g;
$('#title').keyup(function (e) {
var which = e.which;
//avoid useless replacements when <- and -> keys are pressed
if (which === 39 || which === 37) return;
this.value = this.value.replace(cleanRx, '');
}).trigger('keyup'); //perform replacement on initial content (remove if uneeded)
$('#description1').keyup(function (e) {
var which = e.which;
//avoid useless replacements when <- and -> keys are pressed
if (which === 39 || which === 37 || which === 13) return;
this.value = this.value.replace(cleanRx, '');
}).trigger('keyup'); //perform replacement on initial content (remove if uneeded)
});

add this code in js
$('#description1').keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
This is your updated JsFiddle http://jsfiddle.net/pratbhoir/FPN9w/3/

Related

How to get keys pressed before enter with jQuery

Sorry if this question has already been asked, I am trying to create an app where the user scans a bar code and the data is then shown on the screen. I don't want to use textbox's because I don't want the data to be editable.
So far I've managed to get the enter key which is automatically sent at the end of the barcode but can't seem to get the keys pressed before, any help would be massively appreciated!
var item = "";
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item);
}else{
item = item + e.which();
}
});
Just to clarify what I want to do is show an alert box with the keys pressed before enter! For example : A B C D ENTER would show an alert("ABCD")
Thanks!
UPDATE
So got my code to work but I'm getting "undefinedTHEKEYSPRESEDHERE" as the return:
var counter = 0;
var item = [];
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item[counter]);
counter++;
}else{
item[counter] = item[counter] + String.fromCharCode(e.which);
}
});
Obviously this isn't clear enough, so I've outlined my problem below:
What I'm getting from alert(item[counter]);:
undefinedKEYS
What I want from alert(item[counter]);:
KEYS
So from undefinedKEYS to just KEYS I need to remove the text "undefined".
Clear enough?
Change e.which() to String.fromCharCode(e.which).
http://jsfiddle.net/8msksn3a/
var item = "";
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item);
}else{
item = item + String.fromCharCode(e.which);
}
});
Not that I recommend this way of checking for previous results, but you are basically resetting item to "" inside the keypress event. Set it once outside the event.
which is a property, not a method:
Convert from ASCII to string char with string.fromCharCode (A google search would have given you that in two seconds).
Use (e.which || e.keyCode) to ensure you get the keycode on all browsers.
e.g.
var item = "";
$(document).keypress(function(e) {
if((e.which || e.keyCode) == 13) {
alert(item);
}else{
item = item + String.fromCharCode(e.which || e.keyCode);
}
});
Copy paste to your console and run:
var keys = [];
$(document).keypress(function(e) {
var keyChar;
if(e.which == 13) {
console.log( keys.join('') );
keys.length = 0;
}
else{
keyChar = String.fromCharCode(e.which);
if( keyChar )
keys.push( keyChar );
}
});
This technique will not show keys which does not have a textual character assigned to them (like the F1-F12 keys for example)

jQuery Crashes on .live("keyup")

I have some code here:
$(document).ready(function() {
$("#querybox").live("keyup", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$("#querybox").blur();
}
else {
search(document.getElementById('querybox').value);
}
/*if (document.getElementById('querybox').value == "") {
$("center").removeHighlight();
}*/
});
});
that detects a keyUp and uses it to search something. The problem is: when the #querybox is backspaced to the point where it is empty, the entire page crashes and I get the "Awwww, Snap!" message from Google Chrome.
I am using jQuery v1.7.2
Thx a million!
EDIT
I should also point out that the search() function highlights text in the body (notice the commented section). I am using the highlight plugin...
Search Fn:
function search(query) {
$("center").removeHighlight();
$(".paragraph").highlight(query);
$(".highlight").each(function (index) {
$(this).attr("id", "tmpforgoToByClassScrollhighlight" + index);
});
}
Try using .on(...) instead:
$("#querybox").on("keyup", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var queryBox = this;
if (code === 13) { // PRESSED ENTER
queryBox.blur();
}
else {
search(queryBox.val());
}
});
After your update:
You might want to look better into how you do your search functiom.
Cache some of those jQuery elements so you do not keep selecting them over and over on each keyup.
Also, I am not going through all of the .highlight code, but there probably is a bug in there that does not allow for an empty string, and that is why the website is causing the browser to crash.
You should use .delegate() instead
$(document).ready(function() {
//It will be a good advice to replace body with a parent element of #querybox
$("body").delegate("#querybox","keyup", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$("#querybox").blur();
}
else {
search(document.getElementById('querybox').value);
}
/*if (document.getElementById('querybox').value == "") {
$("center").removeHighlight();
}*/
});
});

Need help in regex

Will this code block $ % # or ( as I type?
var digitsOnly = /[0-9]/g;
var emailOnly = /[a-zA-Z0-9_.#-]/g;
var alphaOnly = /[a-zA-Z]/g;
var dateOnly = /[0-9\/]/g;
function restrictKeys(myfield, e, restrictionType) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if they pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if they are press other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
return true;
} else {
return false;
}
}
}
Will this code block $ % # or ( as I
type?
No. Detecting keys pressed is futile, users can paste or drag text into form controls so the key codes don't match the text being entered (or not fire a key event at all). Also, you only care about the value when the form is submitted, whatever value it has in the meantime is irrelevant to you.
Validate form control content on submit, restricting keyboard entry by any means is very, very annoying for users and easily bypassed.

Cancel the keydown in HTML

How can I cancel the keydown of a specific key on the keyboard, for example(space, enter and arrows) in an HTML page.
If you're only interested in the example keys you mentioned, the keydown event will do, except for older, pre-Blink versions of Opera (up to and including version 12, at least) where you'll need to cancel the keypress event. It's much easier to reliably identify non-printable keys in the keydown event than the keypress event, so the following uses a variable to set in the keydown handler to tell the keypress handler whether or not to suppress the default behaviour.
Example code using addEventListener and ignoring ancient version of Opera
document.addEventListener("keydown", function(evt) {
// These days, you might want to use evt.key instead of keyCode
if (/^(13|32|37|38|39|40)$/.test("" + evt.keyCode)) {
evt.preventDefault();
}
}, false);
Original example code from 2010
var cancelKeypress = false;
document.onkeydown = function(evt) {
evt = evt || window.event;
cancelKeypress = /^(13|32|37|38|39|40)$/.test("" + evt.keyCode);
if (cancelKeypress) {
return false;
}
};
/* For pre-Blink Opera */
document.onkeypress = function(evt) {
if (cancelKeypress) {
return false;
}
};
Catch the keydown event and return false. It should be in the lines of:
<script>
document.onkeydown = function(e){
var n = (window.Event) ? e.which : e.keyCode;
if(n==38 || n==40) return false;
}
</script>
(seen here)
The keycodes are defined here
edit: update my answer to work in IE
This is certainly very old thread.
In order to do the magic with IE10 and FireFox 29.0.1 you definitely must do this inside of keypress (not keydown) event listener function:
if (e.preventDefault) e.preventDefault();
jQuery has a nice KeyPress function which allows you to detect a key press, then it should be just a case of detecting the keyvalue and performing an if for the ones you want to ignore.
edit:
for example:
$('#target').keypress(function(event) {
if (event.keyCode == '13') {
return false; // or event.preventDefault();
}
});
Just return false. Beware that on Opera this doesn't work. You might want to use onkeyup instead and check the last entered character and deal with it.
Or better of use JQuery KeyPress
I only develop for IE because my works requires it, so there is my code for numeric field, not a beauty but works just fine
$(document).ready(function () {
$("input[class='numeric-field']").keydown(function (e) {
if (e.shiftKey == 1) {
return false
}
var code = e.which;
var key;
key = String.fromCharCode(code);
//Keyboard numbers
if (code >= 48 && code <= 57) {
return key;
} //Keypad numbers
else if (code >= 96 && code <= 105) {
return key
} //Negative sign
else if (code == 189 || code == 109) {
var inputID = this.id;
var position = document.getElementById(inputID).selectionStart
if (position == 0) {
return key
}
else {
e.preventDefault()
}
}// Decimal point
else if (code == 110 || code == 190) {
var inputID = this.id;
var position = document.getElementById(inputID).selectionStart
if (position == 0) {
e.preventDefault()
}
else {
return key;
}
}// 37 (Left Arrow), 39 (Right Arrow), 8 (Backspace) , 46 (Delete), 36 (Home), 35 (End)
else if (code == 37 || code == 39 || code == 8 || code == 46 || code == 35 || code == 36) {
return key
}
else {
e.preventDefault()
}
});
});

Allow text box only for letters using jQuery?

I want to make a text box allow only letters (a-z) using jQuery.
Any examples?
<input name="lorem" onkeyup="this.value=this.value.replace(/[^a-z]/g,'');">
And can be the same to onblur for evil user who like to paste instead of typing ;)
[+] Pretty jQuery code:
<input name="lorem" class="alphaonly">
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') ); }
);
</script>
Accepted answer
The accepted answer may be short, but it is seriously flawed (see this fiddle):
The cursor moves to the end, no matter what key is pressed.
Non-letters are displayed momentarily, then disappear.
It is problematic on Chrome for Android (see my comment).
A better way
The following creates an array of key codes (a whitelist). If the key pressed is not in the array, then the input is ignored (see this fiddle):
$(".alpha-only").on("keydown", function(event){
// Allow controls such as backspace, tab etc.
var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];
// Allow letters
for(var i = 65; i <= 90; i++){
arr.push(i);
}
// Prevent default if not in array
if(jQuery.inArray(event.which, arr) === -1){
event.preventDefault();
}
});
Note that this allows upper-case and lower-case letters.
I have included key codes such as backspace, delete and arrow keys. You can create your own whitelist array from this list of key codes to suit your needs.
Modify on paste only
Of course, the user can still paste non-letters (such as via CTRL+V or right-click), so we still need to monitor all changes with .on("input"... but replace() only where necessary:
$(".alpha-only").on("input", function(){
var regexp = /[^a-zA-Z]/g;
if($(this).val().match(regexp)){
$(this).val( $(this).val().replace(regexp,'') );
}
});
This means we still have the undesired effect of the cursor jumping to the end, but only when the user pastes non-letters.
Avoiding autocorrect
Certain touchscreen keyboards will do everything in their power to autocorrect the user wherever it deems necessary. Surprisingly, this may even include inputs where autocomplete and autocorrect and even spellcheck are off.
To get around this, I would recommend using type="url", since URLs can accept upper and lower case letters but won't be auto-corrected. Then, to get around the browser trying to validate the URL, you must use novalidate in your form tag.
To allow only lower case alphabets, call preventDefault on the event object if the key code is not in the range 'a'..'z'. Check between 65..90 or 'A'..'Z' too if upper case should be allowed.
Or, alternatively use one of the many input mask plugins out there.
See example.
​$(<selector>).keypress(function(e) {
if(e.which < 97 /* a */ || e.which > 122 /* z */) {
e.preventDefault();
}
});​​​​​
// allow only Alphabets A-Z a-z _ and space
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^A-Za-z_\s]/,'') ); } // (/[^a-z]/g,''
);
// allow only Number 0 to 9
$('.numberonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^0-9]/,'') ); } // (/[^a-z]/g,''
);
Demonstrated below to allow only letters [a-z] using Jquery:
$(function() {
$('#txtFirstName').keydown(function(e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input id="txtFirstName" value="">
Solution described by #dev-null-dweller is working absolutely.
However, As of jQuery 3.0, .bind() method has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
Check deprecated methods list for jQuery 3.0 here: http://api.jquery.com/category/deprecated/deprecated-3.0/
So the solution is to use .on() method instead .bind().
If you need to bind existing elements then the code will be :
$('.alphaonly').on('keyup blur', function(){
var node = $(this);
node.val( node.val().replace(/[^a-z]/g,'') );
});
If you need to bind to dynamic elements the code will be :
$(document).on('keyup blur', '.alphaonly', function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') );
});
You need to bind the event to document or some other element that already exist from the document load.
Hope this is helpful for new version of jQuery.
$("#test").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test1").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test3").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32)||(inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For letters:<input type="text" id="test"> <br>
<br>
For Numbers: <input type="text" id="test1">
<br>
<br>
For Alphanumeric: <input type="text" id="test3">
Thanks to the first answer.. made this..
<input name="lorem" class="alpha-only">
<script type="text/javascript">
$(function()
{
$('.alpha-only').bind('keyup input',function()
{
if (this.value.match(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g))
{
this.value = this.value.replace(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g, '');
}
});
});
</script>
This has some improvements like letters with accents, and changing "blur" for "input" corrects the Non-letters displayed momentarily, also when you select text with the mouse and dragging is corrected..
JQuery function to allow only small and Capital Letters:
Text Field:
<input id="a" type="text" />
JQuery Function:
$('#a').keydown(function (e) {
if (e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
Supports backspace:
new RegExp("^[a-zA-Z \b]*$");
This option will not check mobile. So you can use a jQuery Mask Plugin and use following code:
jQuery('.alpha-field, input[name=fname]').mask('Z',{translation: {'Z': {pattern: /[a-zA-Z ]/, recursive: true}}});
$("#txtName").keypress(function (e) {
var key = e.keyCode;
if ((key >= 48 && key <= 57) || (key >= 33 && key <= 47) || (key >= 58 && key <= 64) || (key >= 91 && key <= 96) || (key >= 123 && key <= 127)) {
e.preventDefault();
}
var text = $(this).val();
$(this).val(text.replace(" ", " "));
});
if (!isValidName(name)) {
//return fail message
} else {
//return success message
}
function isValidName(name) {
var regex = new RegExp("^[a-zA-Z ]+$");
if (regex.test(name)) {
return true;
} else {
return false;
}
}

Categories