make on keyup only fire once inside of an input - javascript

I have this method:
jQuery(function($) {
var input = $('#search');
input.on('keyup', function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 ) {
console.log('ajax request cancelled');
recentRequest.abort();
}
});
});
but as of right now everytime I press Backspace it will fire, I want to make it so it can only be fired once inside of my input. Anyone have an idea?
Thanks

You can create a backspaceFlag variable to ensure that backspace code is allowed/triggered only once:
jQuery(function($) {
var backspaceFlag = true;
var input = $('#search');
input.on('keyup', function() {
var key = event.keyCode || event.charCode;
if ((key == 8 || key == 46) && backspaceFlag) {
backspaceFlag = false;
console.log('ajax request cancelled');
recentRequest.abort();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='search' />

Related

Jquery - append after remove

after press key "," i append new input, when i use backspace last input is removed, but after delete all inputs when i press again "," code return all inputs, not one. how fix it?
http://jsfiddle.net/3r79hyoL/
$(".multipleField").keyup(function(e) {
var key = e.which ? e.which : event.keyCode;
if (key == 110 || key == 188) {
e.preventDefault();
var value = $(this).val();
$(this).val(value.replace(",", ""));
$(this).first().clone().appendTo(".multipleFields").focus().val("");
event.preventDefault();
$(this).addClass('makeBorder');
replaceAndCopy();
}
if (key == 8) {
e.preventDefault();
if ($(".multipleFields").last().val() == "" && $(".multipleField").length > 1) {
$(".multipleField").last().remove();
$(".multipleField").last().focus();
}
}
});
function replaceAndCopy() {
$(".multipleField").keyup(function(e) {
var key = e.which ? e.which : event.keyCode;
if (key == 110 || key == 188) {
e.preventDefault();
var value = $(this).val();
$(this).val(value.replace(",", ""));
$(this).clone().appendTo(".multipleFields").focus().val("");
$(this).addClass('makeBorder');
replaceAndCopy();
}
if (key == 8) {
if ($(".multipleFields").last().val() == "" &&
$(".multipleField").length != 1) {
$(".multipleField:last").remove();
e.preventDefault();
$(".multipleField").last().focus();
}
}
});
}
The problem is that you are attaching new event listeners to every input. So when you go back to an input that is not the last one the event is fired more than one time.
function replaceAndCopy() {
// Add new event listener to all inputs, instead of the last
// $(".multipleField").keyup(function(e) {
// Change to
$(".multipleField").last().keyup(function(e) {
var key = e.which ? e.which : event.keyCode;
if (key == 110 || key == 188) {
e.preventDefault();
var value = $(this).val();
$(this).val(value.replace(",", ""));
$(this).clone().appendTo(".multipleFields").focus().val("");
$(this).addClass('makeBorder');
replaceAndCopy();
}
if (key == 8) {
if ($(".multipleFields").last().val() == "" && $(".multipleField").length != 1) {
$(".multipleField:last").remove();
e.preventDefault();
$(".multipleField").last().focus();
}
}
});

How can I use keyup and down true false

I have the following code to allow user to enter single digit code in an input box, if user presses delete key, then, I would like to recheck some condition and allow user type again. How do I do it?:
$('.code').bind('keyup', function(event) {
var value = $(this).val();
console.log("value.." + value.length);
if (value.length === 1) {
$('.InputInsertCodeLast').bind('keydown', function(event) {
var code = event.keyCode || event.which;
console.log('You pressed a "key" key in textbox' + event.keyCode);
if ((code === 8 || code === 46) || (value.length === 0)) {
return true;
} else {
//code to not allow any changes to be made to input field
return false;
}
});
} else if (value.length === 0) {
console.log("value.length,,0");
$('.InputInsertCodeLast').bind('keydown', function(event) {
console.log("value.length,22,0");
return true;
});
}
});
https://plnkr.co/edit/SpjcKkTA4UaJ0GzzEuYf?p=info
window.onload = function() {
window.addEventListener('keydown', function(event) {
event.preventDefault();
if(event.key === 'Backspace'){
console.log('backspace');
}
});
}
of course this is just a suggest to give an idea how things work, you can workout a more efficent solution based on this :)

jQuery do not allow alphabets to be entered in input field

My requirement is to not allow user to type in any Alphabets. The below code allows 1 character to be entered even though I have provided the e.preventDefault() method on both keydown and keyup methods.
$(function() {
// Regular Expression to Check for Alphabets.
var regExp = new RegExp('[a-zA-Z]');
$('#test').on('keydown keyup', function(e) {
var value = $(this).val();
// Do not allow alphabets to be entered.
if (regExp.test(value)) {
e.preventDefault();
return false;
}
}); // End of 'keydown keyup' method.
}); // End of 'document ready'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" name="test" />
What am I doing wrong? Is there some other way to get this done?
Replace
var value = $(this).val();
by
var value = String.fromCharCode(e.which) || e.key;
After all, you need to check which key has been pressed before allowing a character to be typed into the field.
Also, make sure the backspace and delete buttons and arrow keys aren’t blocked!
$(function() {
var regExp = /[a-z]/i;
$('#test').on('keydown keyup', function(e) {
var value = String.fromCharCode(e.which) || e.key;
// No letters
if (regExp.test(value)) {
e.preventDefault();
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" name="test" />
If your goal is to only accept numbers, dots and commas use this function instead:
$(function() {
var regExp = /[0-9\.\,]/;
$('#test').on('keydown keyup', function(e) {
var value = String.fromCharCode(e.which) || e.key;
console.log(e);
// Only numbers, dots and commas
if (!regExp.test(value)
&& e.which != 188 // ,
&& e.which != 190 // .
&& e.which != 8 // backspace
&& e.which != 46 // delete
&& (e.which < 37 // arrow keys
|| e.which > 40)) {
e.preventDefault();
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" name="test" />
You need to store input data somewhere and update it each time user inputs allowed character or reset when disabled
$(function() {
// Regular Expression to Check for Alphabets.
var regExp = new RegExp('[a-zA-Z]'),
inputVal = '';
$('#test').on('keydown keyup', function(e) {
var value = $(this).val();
// Do not allow alphabets to be entered.
if (regExp.test(value)) {
$(this).val(inputVal)
}
else{
inputVal = value
}
}); // End of 'keydown keyup' method.
}); // End of 'document ready'
Create a function that will mask it out
jsfiddle
$.fn.noMask = function(regex) {
this.on("keypress", function(e) {
if (regex.test(String.fromCharCode(e.which))) {
return false;
}
});
}
$("input").noMask ( /[a-zA-Z]/ );
If you are trying for only alphabet with space you can try it:
$("#test").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^a-zA-Z ]/, ""));
if (!((event.charCode > 64 &&
event.charCode < 91) || event.charCode ==32 || (event.charCode > 96 &&
event.charCode < 123))) {
event.preventDefault();
}
});
This code will allow only numbers to be accepted for example in a telepone number input field. This is the improvement on the accepted answer.
var regExp = /[0-9]/;
$("#test").on('keydown keyup blur focus', function(e) {
var value =e.key;
/*var ascii=value.charCodeAt(0);
$('textarea').append(ascii);
$('textarea').append(value);
console.log(e);*/
// Only numbers
if (!regExp.test(value)
&& e.which != 8 // backspace
&& e.which != 46 // delete
&& (e.which < 37 // arrow keys
|| e.which > 40)) {
e.preventDefault();
return false;
}
});

Control+backspace in textbox javascript

I have a requirement of having a text-box with default value say "PF_". If I type something and press control+backspace All the values are been deleted. This problem occurs only If I have an underscore "_" at the end.
Javascript
var readOnlyLength = $('#field').val().length;
$('#output').text(readOnlyLength);
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39)) && ((this.selectionStart < readOnlyLength) || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
return false;
}
});
Html
<input id="field" type="text" value="PF_" size="50" />
I have tried a sample fiddle.
Any Idea?
I'm not sure if this is what you're after, but this will reset the field to the previous value if the user tries to modify the read-only part:
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
var old = $field.val();
setTimeout(function(){
if($field.val().slice(0,3)!='PF_') {
$field.val(old);
}
},0);
});
Edit: in response to op's comments, try this code instead:
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
if(event.ctrlKey && event.which==8) { // ctrl-backspace
$field.val('PF_');
return false;
}
var old = $field.val();
setTimeout(function(){
if($field.val().slice(0,3)!='PF_') {
$field.val(old);
}
},0);
});
Fiddle
This is how I would do it:
$("#field").keyup(function(e){
if($(this).val().length < 3){
$(this).val("PF_");
}
});
Here is the JSFiddle demo

How to limit Tab listener to callback only if the textbox has change

I'm trying to implement a Tab key listener for a textbox.
$('#mytextbox').live('keydown', function (e) {
if (e.keyCode == 9 || e.which == 9) {
// TO DO SOMETHING
}
});
However, for some reason I need to limit the tab listener's callback to invoke only when the textbox has changed. Is there anyway to do this?
You might be able to check the value of the input field to make sure it's different from it's original value?
E.g.
$('#mytextbox').live('keydown', function (e) {
if ((e.keyCode == 9 || e.which == 9) && ($('#TextBox').val() != 'Starting Value')) {
// TO DO SOMETHING
}
});
You can do it just like:
var data = "";
$('#mytextbox').live('keydown', function (e){
if(e.which == 9 || e.keyCode == 9){
if($(this).val() != data){
alert('changed!');
data = $(this).val();
}
}
});
http://jsfiddle.net/DDCZS/1/
Or without storing / knowing value of that textbox:
var changed = false;
$('#mytextbox').on('keydown', function (e) {
if (e.which == 9 && changed) {
e.preventDefault();
// TO DO SOMETHING
alert("works");
changed = false;
} else {
changed = true;
}
});
http://jsfiddle.net/9a37b/

Categories