Cannot clear textbox after keypress event - javascript

I know this questions is all over the place, but this is driving me crazy!!!
Here is my code:
$(document).ready(function () {
$('#MainContent_LoginUser_Password').keypress(function (e) {
noCapsLock($('#MainContent_LoginUser_Password'), e, "Please turn off Caps Lock");
});
});
function noCapsLock(o, e, str) {
var s = String.fromCharCode(e.which);
if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
alert(str);
o.val('');
}
}
I am trying to clear the value of the textbox with the given id. The code above clears the text, but when a new key is pressed, the value of that key is shown (uppercase letters).
I have tried the change(), keyup(), keydown() functions but they still do not seem to clear the textbox of the last value entered.
Any help will be appreciated. Thank you!

You just need to add an event.preventDefault();
You might also want to place your function inside the closure so it isn't global, and you don't need to re-find the html element again inside the method:
$(document).ready(function () {
var noCapsLock = function(o, e, str) {
var s = String.fromCharCode(e.which);
if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
alert(str);
o.val('');
e.preventDefault();
}
}
$('#MainContent_LoginUser_Password').keypress(function (e) {
noCapsLock($(this), e, "Please turn off Caps Lock");
});
});
For kicks I also made your code into a jQuery plugin that you can easily apply to any element (it doesn't delete the value just stops the keypress):
(function($) {
$.fn.noCapsLock = function(message) {
this.keypress(function (e) {
var char = String.fromCharCode(e.which);
if (char.toUpperCase() === char && char.toLowerCase() !== char && !e.shiftKey) {
window.alert(message);
e.preventDefault();
}
});
};
})(jQuery);
Apply like this:
$(document).ready(function () {
$('#MainContent_LoginUser_Password').noCapsLock('Please turn off Caps Lock!');
});

You just have to cancel the event with e.preventDefault();:
function noCapsLock(o, e, str) {
var s = String.fromCharCode(e.which);
if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
e.preventDefault();
alert(str);
o.val('');
}
}

I would not clear the textbox in your case; if user types long text in lower case, then hits CapsLock and then continues typing - the whole input will be deleted.
As for the function, you can either call event's preventDefault() method or return false (you can read here on the differences between the methods):
$(document).ready(function () {
$('#MainContent_LoginUser_Password').keypress(function (e) {
return noCapsLock(e, "Please turn off Caps Lock");
});
});
function noCapsLock(e, str) {
var s = String.fromCharCode(e.which);
if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
alert(str);
return false;
}
return true;
}

Related

jQuery: selectionStart returns undefined

Situation
browser
Google Chtome 69
html
<textarea id="message" name="message">
// input some messsage
</textarea>
js(jQuery)
$(function () {
$("#message").on("keydown keyup keypress change", function () {
//this part runs correctly
})
$('#message').on('keydown', function (e) {
if ((e.wich && e.wich === 13) || (e.keyCode && e.keyCode === 13)) {
var $textarea = $(this);
var sentence = $textarea.val();
var position = $textarea.selectionStart;
var length = sentence.length;
var before = sentence.substr(0, position);
var after = sentence.substr(position, length);
sentence = before + "\n" + after;
}
});
});
When I input something in the #message textarea and push Enter key in the area, nothing would happen. According to Chrome developer tool, selectionStart method seems to return Undefined.
Needs
Enter key has been made disabled in this form page in order to avoid submitting the data mitakenly.
js
function fnCancelEnter()
{
if (gCssUA.indexOf("WIN") != -1 && gCssUA.indexOf("MSIE") != -1) {
if (window.event.keyCode == 13)
{
return false;
}
}
return true;
}
However, in this textarea, I want to enable user to add a break line by pressing Enter key.
I'm sorry but I don't have much knowledge about jQuery and javascript. Please tell me how to do.
Please replace $textarea.selectionStart by $textarea.get(0).selectionStart. Then try again.

delete element using remove() while clicking and pressing a key

I want to add a delete mode that the user can enter by pressing a certain key (Im using the key "enter" for now e.which == 13 checks if the key pressed is enter in the below sample)
var checker = 1;
$(document).keypress(function (e) {
if (e.which == 13 && checker == 1) {
checker = 2;
alert("entered delete mode");
$(".element1").click(function (e) {
$(this).remove();
});
}
else if (e.which == 13 && checker == 2) {
checker = 1;
alert("exited delete mode");
$(".element1").each(function (i, e) {
$(this).off("click", "**");
});
};
});
So basically when the user presses enter I check if we are in the delete mode already, if not (checker ==1) we enter it and I add a function on click() for objects with class ".element1"
If the user is in not in delete mode (checker==2), I try to remove the click method.
But for some reason this part does not work.
Thank you all.
EDIT
I also tried to add .click to the .element class: (this way in my mind it should've deleted the element when I hover and press enter)
$(.element1)
.hover(function (e) {
var deletable = $(this);
$(document).keypress(function (e) {
if (e.which == 13) {
deletable.remove();
}
});
});
but whenever I press enter it just deletes all .elements
Any way works for me.
You can't have a second argument on the .off(). Fixed code:
var checker = 1;
$(document).keypress(function (e) {
if (e.which == 13 && checker == 1) {
checker = 2;
alert("entered delete mode");
$(".element1").click(function (e) {
$(this).remove();
});
}
else if (e.which == 13 && checker == 2) {
checker = 1;
alert("exited delete mode");
$(".element1").off("click");
};
});
I also got rid of the second .each(), as suggested in the comments (it wasn't necessary).
Try using on/off like this and not removing the element:
var checker = 1;
$(document).keypress(function (e) {
if (e.which == 13 && checker == 1) {
checker = 2;
alert("entered delete mode");
$(".element1").on('click', function (e) {
// handle click
});
}
else if (e.which == 13 && checker == 2) {
checker = 1;
alert("exited delete mode");
$(".element1").off('click', '**');
};
});

jquery scannerDetection ignoreIfFocusOn:'input' not working

I am using scannerDetection.js to scan barcodes:
jQuery(document).ready(function () {
$(document).scannerDetection({ ignoreIfFocusOn: 'input[type="text"]' });
});
But the above setting does not work, as every time i focus an input element the barcode is displayed in the input box, plus form submit event is fired as well.
I tried using: $(document).scannerDetection({ preventDefault:true });
Which works, but unfortunately it also blocks my keyboard input.
I tried using different versions of jquery library with no success.
According to this article, plug-in and its settings should work just fine.
I tried looking at the source code for the plugin, but cannot quite figure it out:
(function ($) {
$.fn.scannerDetection = function (options) {
// If string given, call onComplete callback
if (typeof options === "string") {
this.each(function () {
this.scannerDetectionTest(options);
});
return this;
}
// If false (boolean) given, deinitialize plugin
if (options === false) {
this.each(function () {
this.scannerDetectionOff();
});
return this;
}
var defaults = {
onComplete: false, // Callback after detection of a successfull scanning (scanned string in parameter)
onError: false, // Callback after detection of a unsuccessfull scanning (scanned string in parameter)
onReceive: false, // Callback after receiving and processing a char (scanned char in parameter)
onKeyDetect: false, // Callback after detecting a keyDown (key char in parameter) - in contrast to onReceive, this fires for non-character keys like tab, arrows, etc. too!
timeBeforeScanTest: 100, // Wait duration (ms) after keypress event to check if scanning is finished
avgTimeByChar: 30, // Average time (ms) between 2 chars. Used to do difference between keyboard typing and scanning
minLength: 6, // Minimum length for a scanning
endChar: [9, 13], // Chars to remove and means end of scanning
startChar: [], // Chars to remove and means start of scanning
ignoreIfFocusOn: false, // do not handle scans if the currently focused element matches this selector
scanButtonKeyCode: false, // Key code of the scanner hardware button (if the scanner button a acts as a key itself)
scanButtonLongPressThreshold: 3, // How many times the hardware button should issue a pressed event before a barcode is read to detect a longpress
onScanButtonLongPressed: false, // Callback after detection of a successfull scan while the scan button was pressed and held down
stopPropagation: false, // Stop immediate propagation on keypress event
preventDefault: false // Prevent default action on keypress event
};
if (typeof options === "function") {
options = { onComplete: options }
}
if (typeof options !== "object") {
options = $.extend({}, defaults);
} else {
options = $.extend({}, defaults, options);
}
this.each(function () {
var self = this, $self = $(self), firstCharTime = 0, lastCharTime = 0, stringWriting = '', callIsScanner = false, testTimer = false, scanButtonCounter = 0;
var initScannerDetection = function () {
firstCharTime = 0;
stringWriting = '';
scanButtonCounter = 0;
};
self.scannerDetectionOff = function () {
$self.unbind('keydown.scannerDetection');
$self.unbind('keypress.scannerDetection');
}
self.isFocusOnIgnoredElement = function () {
if (!options.ignoreIfFocusOn) return false;
if (typeof options.ignoreIfFocusOn === 'string') return $(':focus').is(options.ignoreIfFocusOn);
if (typeof options.ignoreIfFocusOn === 'object' && options.ignoreIfFocusOn.length) {
var focused = $(':focus');
for (var i = 0; i < options.ignoreIfFocusOn.length; i++) {
if (focused.is(options.ignoreIfFocusOn[i])) {
return true;
}
}
}
return false;
}
self.scannerDetectionTest = function (s) {
// If string is given, test it
if (s) {
firstCharTime = lastCharTime = 0;
stringWriting = s;
}
if (!scanButtonCounter) {
scanButtonCounter = 1;
}
// If all condition are good (length, time...), call the callback and re-initialize the plugin for next scanning
// Else, just re-initialize
if (stringWriting.length >= options.minLength && lastCharTime - firstCharTime < stringWriting.length * options.avgTimeByChar) {
if (options.onScanButtonLongPressed && scanButtonCounter > options.scanButtonLongPressThreshold) options.onScanButtonLongPressed.call(self, stringWriting, scanButtonCounter);
else if (options.onComplete) options.onComplete.call(self, stringWriting, scanButtonCounter);
$self.trigger('scannerDetectionComplete', { string: stringWriting });
initScannerDetection();
return true;
} else {
if (options.onError) options.onError.call(self, stringWriting);
$self.trigger('scannerDetectionError', { string: stringWriting });
initScannerDetection();
return false;
}
}
$self.data('scannerDetection', { options: options }).unbind('.scannerDetection').bind('keydown.scannerDetection', function (e) {
// If it's just the button of the scanner, ignore it and wait for the real input
if (options.scanButtonKeyCode !== false && e.which == options.scanButtonKeyCode) {
scanButtonCounter++;
// Cancel default
e.preventDefault();
e.stopImmediatePropagation();
}
// Add event on keydown because keypress is not triggered for non character keys (tab, up, down...)
// So need that to check endChar and startChar (that is often tab or enter) and call keypress if necessary
else if ((firstCharTime && options.endChar.indexOf(e.which) !== -1)
|| (!firstCharTime && options.startChar.indexOf(e.which) !== -1)) {
// Clone event, set type and trigger it
var e2 = jQuery.Event('keypress', e);
e2.type = 'keypress.scannerDetection';
$self.triggerHandler(e2);
// Cancel default
e.preventDefault();
e.stopImmediatePropagation();
}
// Fire keyDetect event in any case!
if (options.onKeyDetect) options.onKeyDetect.call(self, e);
$self.trigger('scannerDetectionKeyDetect', { evt: e });
}).bind('keypress.scannerDetection', function (e) {
if (this.isFocusOnIgnoredElement()) return;
if (options.stopPropagation) e.stopImmediatePropagation();
if (options.preventDefault) e.preventDefault();
if (firstCharTime && options.endChar.indexOf(e.which) !== -1) {
e.preventDefault();
e.stopImmediatePropagation();
callIsScanner = true;
} else if (!firstCharTime && options.startChar.indexOf(e.which) !== -1) {
e.preventDefault();
e.stopImmediatePropagation();
callIsScanner = false;
} else {
if (typeof (e.which) != 'undefined') {
stringWriting += String.fromCharCode(e.which);
}
callIsScanner = false;
}
if (!firstCharTime) {
firstCharTime = Date.now();
}
lastCharTime = Date.now();
if (testTimer) clearTimeout(testTimer);
if (callIsScanner) {
self.scannerDetectionTest();
testTimer = false;
} else {
testTimer = setTimeout(self.scannerDetectionTest, options.timeBeforeScanTest);
}
if (options.onReceive) options.onReceive.call(self, e);
$self.trigger('scannerDetectionReceive', { evt: e });
});
});
return this;
}
})(jQuery);
Any suggestions?
The original source code contained this line of code:
.bind('keypress.scannerDetection',function(e){
if (this.isFocusOnIgnoredElement()) return;
As you can see, it returns nothing. Just add false after the return statement:
.bind('keypress.scannerDetection',function(e){
if (this.isFocusOnIgnoredElement()) return true;
That worked for me. Although there is another issue:
barcode appears on focused input field

Deleting Single Element From Same Function

For the following code:
document.getElementById('text_one').onkeypress = function (e) {
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13') {
text = document.getElementById('text_one').value;
if (text == "" || text === null || text.length > 50) {
$('#error_msg').show('slow');
document.getElementById('text_one').disabled = true;
document.getElementById('text_one').value = "";
return false;
} else {
$('#list').append('<li>' + text + '</li><br />');
document.getElementById('text_one').value = "";
}
}
};
How would one go about making a function that deletes the element which was clicked? I was thinking that you could somehow create a specific number that increases every time the function is run and use that number to create custom ID's but I'm not sure how to do that.
JS Fiddle: http://jsfiddle.net/2dd5L/ (The CSS is messed up for some reason)
Since you are using jQuery it's very simple (in pure JS also just 2 more lines of code):
$('#list').on('click', 'li', function() {
$(this).remove();
});
Demo: http://jsfiddle.net/2dd5L/1/

Javascript Error in FireFox Not in IE and Chrome

I use the following function for decimal validation.the textbox only allow to enter numbers and .(dot) symbol only.It was working fine in IE and Chrome.My problem is I get event is not defined error.How to solve this?I have the lot of textbox validation.so i Create the decimal validation as common its like,
//Call the Function
$('.decimalValidate').live('keypress',function(){
var decimalid=$(this).attr("id");
var decimalval=$('#'+decimalid).val();
var decimalvalidate=ApplyDecimalFilter(decimalval);
if(decimalvalidate == false)
return false;
});
//Function for Decimal validation.It allows only one . symbol.everything works fine on IE and Chrome
function ApplyDecimalFilter(id)
{
try {
return NewDecimalFilter(id, event);
} catch (e) {
alert(e.message);
}
}
function NewDecimalFilter(o, event) {
if (event.keyCode > 47 && event.keyCode < 58) {
return true;
}
if ((event.keyCode == 8 || event.keyCode == 46) && o.indexOf('.') == -1) {
return true;
}
return false;
}
And i use this decimalValidate class in text box like as,
input type="text" id="InputLoanAmount" class="decimalValidate" style="width:100px"
In firefox, event isn't global. window.event is undefined. You need to pass the event as a parameter. And by the way, you should use .on instead of .live if you use jQuery >= 1.7.
$('.decimalValidate').live('keypress', function (e) {
var decimalid = $(this).attr("id");
var decimalval = $('#' + decimalid).val();
var decimalvalidate = ApplyDecimalFilter(decimalval, e);
if (decimalvalidate == false) return false;
});
function ApplyDecimalFilter(id, event) {
try {
return NewDecimalFilter(id, event);
} catch (e) {
alert(e.message);
}
}
The live demo.

Categories

Resources