JS:
var KEYS = { SPACE: 32 };
var str = $('#id_phone_daytime').val();
$("#id_phone_daytime").keyup(function(e) {
$.trim(str)
$('#id_phone_daytime').val(str);
if (e.keyCode == KEYS.SPACE) {
alert("No space please")
}
});
html:
No space please
The above code is for validating white space for a single input field. It is working fine, but in my application I have 8 more input fields with different ids. I want to validate white space validation for these 8 input fields also.
How to implement the same functionality with minimum amount of code?
Instead of using an id selector (which has to be unique) use a class selector, which can be used to group elements. Try this:
var KEYS = { SPACE: 32 };
$(".no-spaces").keyup(function(e) {
var $this = $(this);
$this.val($.trim($this.val()));
if (e.keyCode == KEYS.SPACE) {
alert("No space please");
}
});
All you need to do now is add class="no-spaces" to the relevant inputs.
var KEYS = { SPACE: 32 };
$(".no-spaces").keyup(function(e) {
this.value=$.trim(this.value);
if (e.keyCode == KEYS.SPACE) {
alert("No space please");
}
});
You can assign multiple selector using class, for example
<input type="text" class="validate_white_space">
and use this class like below.
var str = $('.validate_white_space').val();
$(".validate_white_space").keyup(function(e) {
$.trim(str)
$('#id_phone_daytime').val(str);
if (e.keyCode == KEYS.SPACE) {
alert("No space please");
}
});
Related
I want to make input text box in primefaces which only can take mobile number with country code. The format is +NN-NNNNNNNNNN, e.g., +91-9876123456. User could not type any other characters except the mentioned. I've tried with some Javascript, but the result did not satisfy me.
By, How to disable special characters and alphabets in Primefaces input text?
In this question, they have mentioned all the thing is perfect, but delete and movement of cursor is not happened here.
Moreover I do not want to use inputMask, behavior of this component is not exact with the text, although you have any better suggestion with this component then kindly provide.
If you need to match that exact pattern, I would probably check on every keypress. Just make sure it's clear to the user that they need to match a pattern or they may get annoyed when their keys don't seem to work.
$("#test").on("keypress", function(e) {
var match = [48,49,50,51,52,53,54,55,56,57];
var insert = '';
if (this.value.length >= 14) {
return false;
}
if (this.value.length === 0) {
if (e.which === 43) {
return true;
}
insert = '+'
}
if (this.value.length === 3) {
if (e.which === 45) {
return true;
}
insert = "-";
}
if (match.indexOf(e.which) === -1) {
return false;
}
this.value += insert;
return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test"></input>
You should give a look at Forza, they did some really interesting implementation for phone input with forced synthax like +() ____ ____ :
http://forza.ndevrstudios.com/#/form-masks
I am having a problem validating a textbox to not allow spacing. When the user enters a space I would like it to display an alert message and then clear the textbox, but the textbox doesn't clear. This is what I have so far.
function ValidateSpace () {
var SerNum = document.getElementById("txtbox1")
if (event.keyCode == 32) {
alert("This field may contain no spaces.");
document.getElementById ("txtbox1").value=""
}
}
I have users trying to put multiple entries in this space but it should only accept one. The textbox is for inventory purposes so it would change the nature of the data if I were to remove spaces
I suppose that you have to bind keyDown event on textbox
try this jquery code to remove live the spaces
$("#IdOfTheTextBox").on("keydown", function (e) {
return e.which !== 32;
});
If you can't use jquery try with this javascript function (onkeypress event of textbox)
function NoSpace() {
if (event.keyCode == 32) {
event.returnValue = false;
return false;
}
}
if you want to remove spaces after the input you can do this
var noSpaces = document.getElementById("txtbox1").value.replace(/\s/g, "");
When non-printable char is pressed, it's replaced with let's say for CTRL=17 with "[CTRL]".
Here is code an example
$('#textbox1').keyup(function (event) {
if (8 != event.keyCode) {
if(17==event.keyCode){
$('#textbox1').val($('#textbox1').val()+"[CTRL]")
$('#textbox2').val($('#textbox1').val());
}else{
$('#textbox2').val($('#textbox1').val());
}
} else {
$('#textbox2').val($('#textbox1').val());
}
});
the problem is when user presses backspace the second input must reflect the content of the first one, so "[CTRL]" must be deleted at once like any other chars.
You could make use of the keyCode and/or in combination with charCode (if required). Basic idea would be:
Create a map of all required key codes in an array/object
Handle event for say keydown and listen for keycode
Look for the keycode in your map and if found show it
prevent the default (to prevent e.g. say backspace browsing back)
If not found in map, let the character go thru as usual.
A very basic example:
Demo: http://jsfiddle.net/abhitalks/L7nhZ/
Relevant js:
keyMap = {8:"[Backspace]",9:"[Tab]",13:"[Enter]",16:"[Shift]",17:"[Ctrl]",18:"[Alt]",19:"[Break]",20:"[Caps Lock]",27:"[Esc]",32:"[Space]",33:"[Page Up]",34:"[Page Down]",35:"[End]",36:"[Home]",37:"[Left]",38:"[Up]",39:"[Right]",40:"[Down]",45:"[Insert]",46:"[Delete]"};
$("#txt").on("keydown", function(e) {
// check if the keycode is in the map that what you want
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
// if found add the corresponding description to the existing text
this.value += keyMap[e.keyCode];
// prevent the default behavior
e.preventDefault();
}
// if not found, let the entered character go thru as is
});
Edit: (as per the comments)
The concept remains the same, just copying the value to the second input:
Demo 2: http://jsfiddle.net/abhitalks/L7nhZ/3/
$("#txt1").on("keyup", function(e) {
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
this.value += keyMap[e.keyCode];
e.preventDefault();
}
$("#txt2").val(this.value); // copy the value to the second input
});
Regarding deletion of the description, I could not get it done by caching the last inserted descrition from the map. Somehow, I kept struggling with the regex with a variable. Anyway, a simpler solution is to just add another event handler for keyup with hard-coded map.
Thanks to #serakfalcon for (that simple solution), which we are using here:
$('#txt1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(Tab|Enter|Shift|Ctrl|Alt|Break|Caps Lock|Esc|Space|Page (Up|Down)|End|Home|Left|Up|Right|Down|Insert|Delete)\]$/,' '));
$("#txt2").val(el.val());
}
});
You can check in the keydown for the last character in the input field. If it's a ] you can remove everything from the right to the last found opening bracket [. Unfortunatly this does not work if you're cursor is inside '[ ]'.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var element = $(this),
value = element.val(),
lastChar = value.slice(-1);
if(lastChar == ']') {
var lastIndex = value.lastIndexOf('['),
index = value.length - lastIndex;
element.val(value.slice(0, -index) + "]");
}
}
});
Fiddle
you can always use a regex.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(CTRL|ALT|SHIFT)\]$/,' '));
}
});
fiddle
Edit: combined with abhitalks code
In my Chat application project, I am trying to restrict spaces when the user has just pressed Space and then Enter. pressing Enter will show entered Text into a div. Please see the comments in the code to understand clearly.
#txtmsg --> ID of TextBox field
$('#txtmsg').keypress(function (e)
{
if (e.which == 13)
{
//Disable default function of Enter key
e.preventDefault();
//Checks whether the user has entered any value or not
if ($('#txtmsg').val().length > 0)
{
//if(user has not entered only spaces....)?
//transfers the entered value in the text field to div
chat.server.send($('#txtmsg').val());
$('#txtmsg').val('');
}
}
});
See http://api.jquery.com/jQuery.trim/ :
if($.trim($('#txtmsg').val()) !== "") { ... }
The check would be:
var message = $('#txtmsg').val(); //cache the message
if(message.replace(/\s/g, "").length !== 0) { //if the message has something other than spaces
//send the message
}
Note that /\s/ matches all kinds of white-space characters; tabs, spaces, new lines, (other weird space characters).
Try:
if ($('#txtmsg').val().length > 0 && /^\s+$/.test($('#txtmsg').val()) === false) {
...
}
http://jsfiddle.net/WhP8q/
I'm trying to restrict input to alpha numeric, 0-9, A-Z,a-z.
The ASCII table i'm referencing: http://www.asciitable.com/
Here is what I have so far
$(function() {
$("input").bind("keydown paste", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var c = code;
var letterAllowed = ((c > 47 && c < 58) || (c > 64 && c < 90) || (c > 96 && c < 123))
if (code > 32 && !letterAllowed) {
return false;
}
});
});
right now, the tilde (~) character is prevented from getting input into the field, but other special / shift characters such as !##$% all get entered into the text field.
I'm pretty sure my logic is sound, but my issue is with some misunderstanding of javascript bindings? idk
Preventing character input for only some cases is very complicated in javascript, as in the keypress event (the one you'd want to prevent) you do not know the afterwards value of your input, but only the keycode of the pressed key (and not even the resulting char for sure). Also, you will need to care about special keys like or .
I'd recommend something like this:
$("input").on("keypress keyup paste", function(e) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
In case of restrict the character you enter, You can replace the character which is not alphanumberic.
<input type='text' id="txtAlphaNumeric"/>
<input type='text' id="txtNumeric"/>
<input type='text' id="txtAlphabet"/>
<script type="text/javascript">
$(function() {
$('#txtNumeric').keyup(function() {
if (this.value.match(/[^0-9]/g)) {
this.value = this.value.replace(/[^0-9]/g, '');
}
});
$('#txtAlphabet').keyup(function() {
if (this.value.match(/[^a-zA-Z]/g)) {
this.value = this.value.replace(/[^a-zA-Z]/g, '');
}
});
$('#txtAlphaNumeric').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
});
});
</script>
Answer taken from: jquery allow only alphanumeric
Turns out, I need to do the following:
$("input").keypress(function(e){
var code = e.charCode;
charCode will give the actual character code of the typed letter, rather than the ascii code of the last pressed key
see http://api.jquery.com/keypress/