How to disable/remove only first space on input field? - javascript

Good morning everybody!
I have a case, when I should prevent users to entering space as a first character on input field.
I have a demo here: http://jsbin.com/foyetolo/2/edit
It works only when you hit spacebar for first time. When you start typing other characters and select whole text in input (ctrl+a) and then hit the space bar it adds the space in the beginning of input field.
So, how to check if on keypress/keydown if the first character will be a space, return false and not allow it to type the space as a first character?

You can do this by checking if key is space and selection start is 0 as below:
$(function() {
$('body').on('keydown', '#test', function(e) {
console.log(this.value);
if (e.which === 32 && e.target.selectionStart === 0) {
return false;
}
});
});
Demo Link

This jQuery function selects all the text inputs when a key is unpressed, removes all whitespace from the beginning of the string and replaces the value of the input:
<script>
$(":text").keyup(function () {
$(this).val($(this).val().replace(/^\s+/,""));
}
</script>
I do not recommend to use trim() when blank spaces are replaced directly with keyup() because when you type a space after a word, it will be deleted before you start writing the next word.

Try something like
$('input').keyup(function () {
if($(this).val() == '') {
if(event.keyCode == 32) {
return false;
}
}
}
This would check for current value, and then it would run the function. Keyup is used, to check for the value after the key has been unpressed. If you use keydown, it would still have the value. Key up would get the value after the key press event has passed.
Or as others has told you to always keep trimming the value. You can use jQuery trim() method to trim the value, regardless of whether user inputs space character or not.
$('input').keyup(function () {
$(this).val($.trim($(this).val()));
}
This would add the trimmered form of the value of the current input field.

document.querySelector('#test').addEventListener('input',function(e){
if(e.target.value===" ")
e.target.value="" })
this code dosent let users space at the first even if any users select
whole text in input (ctrl+a) and then hit the space bar

Related

Copy/paste validation on input field and restrict character

I am working on validation of an input control when the user copy paste some value in it
On pasting to this input I want to strip out as below:
Input can start with underscore or an alphabet
Input cannot start with number
Input cannot have any spl character except underscore
Input cannot have spaces
This is allowed:
abc
abc_123
_123bcd
_123_bcd
This is not:
123abc
123_acd
abc s22
I tried with the below code:
#HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.stripInput(event);
}
stripInput(event) {
setTimeout(() => {
this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^A-Za-z ]+/g, '').replace(/\s/g, '');
event.preventDefault();
}, 100);
}
But with above code its not fully working, it doesnt allows:
abc_123
_123_ams
Any inputs please
You have made a simple over sight with regards to your initial regex. You did not add a start of string check (which is needed to remove numbers and extra special characters at the start of the string). You will also need another query if you want to remove other special characters from within the string as well
if you change your last block of code to -
#HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.stripInput(event);
}
stripInput(event) {
setTimeout(() => {
this.el.nativeElement.value = this.el.nativeElement.value.replace(/^[^A-Za-z_]+/g, '').replace(/[^0-9A-Za-z_]+/g, '').replace(/\s/g, '');
event.preventDefault();
}, 100);
}
It should work as expected (Note the extra ^ at the start of the regex and the added _ to your initial regex as well as the extra following regex).
What this does pin the search to the start of the string instead of allowing it to act on all parts of the string. It works on your abc_123 _123_ams input and it also strips the extra space in the middle of it as intended. (it makes it abc_123_123_ams)

Cursor returns to start of contenteditable Div when removing last character

For various reasons I decided to use contenteditable DIV instead of standard form elements, but I ran into a problem. Using Jquery, I'm trying to prevent the div from exceeding the maximum length.
The code works well enough, but when I clip the last character, the cursor returns to the first character in the string. The result is that if someone types past the maximum character point, the string starts to append the new characters typed and truncate what was already there one keystroke at a time.
This is the jquery I'm using:
$('.textarea_text').on('keyup',function() {
var remaining = $(this).data('max') - $(this).html().length;
if (remaining <0)
{
$(this).html($(this).html().slice(0,-1)); // Remove the last character
remaining=0;
}
$(this).closest('.textarea_area').find('.textarea_counter').html("("+remaining+" characters remaining)");
});
JSfiddle: https://jsfiddle.net/cLz7034v/14/
Do not change user input. Just do not allow to enter more characters.
$('.textarea_text').on('keydown',function(e) {//keydown instead of keyup
var remaining = $(this).data('max') - $(this).html().length;
$(this).closest('.textarea_area').find('.textarea_counter').html("("+remaining+" characters remaining)");
//console.log(e.which);
var allowedKeys=[8,35,36,37,38,39,40,46]; //arrows, home, end, del, backspace
if (remaining <=0 && allowedKeys.indexOf(e.which) == -1)
return false;
});

Javascript function For Alpha Numeric in Asp.net [duplicate]

I have a textbox, and it needs not allow the user to enter any special characters. He can enter:
A-Z
a-z
0-9
Space.
One more condition is the first letter should be alphabetic.
How can I do a JavaScript verification on each keypress?
add a onKeyUp="javascript:checkChar(this);" to the input box.
function checkChar(tBox) {
var curVal = tBox.value;
if ( /[^A-Za-z0-9 ]/.test(curVal) ) {
//do something because he fails input test.
}
}
alernatively to check JUST the key that was pressed you can grab the keycode from the event like so:
onKeyUp="javascript:checkChar(event);"
function checkChar(e) {
var key;
if (e.keyCode) key = e.keyCode;
else if (e.which) key = e.which;
if (/[^A-Za-z0-9 ]/.test(String.fromCharCode(key))) {
//fails test
}
}
missed the part about first char, but you can do a test on the textbox value as in the first example:
/^[A-Za-z]/.test(curVal)
or even use the second method but pass the text box as well so you can get it's full value.
This function will check the string given to it for those criteria:
function checkvalue(value) {
return value.match( /[A-Za-z][A-Za-z0-9 ]*/ );
}
You can then use that in an onkeypress event, passing in the current value.
Now that we have HTML5, you don't even need to use JavaScript. You can use the pattern attribute.
<input type="text" pattern="[A-Za-z][A-Za-z0-9 ]*" title="Description of format" />
The pattern attribute should contain a regular expression defining the format. And title should contain a human-readable description of the format.
Then on validation, depending on the browser, the browser will outline the field in red and/or display a message stating your description of the format.
This tutorial goes into more detail: HTML5 Input Validation Tutorial.
You should check pressed key in onkeydown event handler of the textbox and if it doesn't conform conditions then return false from the handler. Using keyup will not allow you to prevent char from being actually inputted in the textbox.
I don't think you should check on each keypress, it could be very annoying for the user.
Just check the input when it loses the focus, or when submiting.
To do it, you can use a regex and use this pattern:
`/[a-z]{1}[a-z0-9]/i`
You can also take a look at the JQuery Validation Plugin

jquery to read and compare a word as you type

I need to implement a sort of word sensing feature . What I require is to have a plugin which will read and compare a word, as I type , with a predefined word , and on successfull matches , it will display a checkbox .
As in the image , once I type test and give a space , it will take the entire word Test and compare it with a predefined word say "Testimony" . Now, as I have given a space after Test , it won't match with the reference word and it will wait for the next word. Again , as a user presses spacebar , it will take the new word and start comparing .
If you need a more customizable option than jQuery's autocomplete, you can bind a keypress event to the textbox you are typing in, check the keycode of the key that the user is pressing, and act accordingly. Something along the lines of this:
$('#textarea').bind('keypress', function(e) {
var key = (e.keyCode ? e.keyCode : e.charCode);
if( key == '32') {
alert("spacebar was pressed");
var input = $("#textArea").val();
// Put your comparison logic here
}
});
I remember there being some funkiness with how IE handles codes, but the above works at least with FF and Chrome.

Counting input chars - use onkeyup or onkeydown?

I need to set the maximum character input for users simililar to how stackoverflow.com works. I plan on using javascript to provide feedback to the user and count the characters. Only submissions that don't exceed the maximum character count are allowed. I don't plan on using the xhtml input properties to limit this amount as I'll allow overage on characters as long as they are not submitted. On the backend I'll just set the varchar field in mysql to charmax.
Question is, how do I count character inputs, do I base it off of onkeydown() or onkeyup(). I'm not too sure why there are two functions, because a key that goes down must come up, so which one should I use to do the counting?
HTML:
<input type='text' id='text'/>
JS:
function textLength(value){
var maxLength = 144;
if(value.length > maxLength) return false;
return true;
}
document.getElementById('text').onkeyup = function(){
if(!textLength(this.value)) alert('text is too long!');
}
Here is a fiddle demo: http://jsfiddle.net/maniator/L2LRK/
Use document.getElementById('YourInputBoxId').value.length to get the length of the text.
Don't use the keyboard events to keep track of the number of characters. Ctrl+V is a single keypress (or two maybe), but it can cause your text to grow megabytes. :)
You could use these events to update a label with the current number of characters.
Apart from onkeyup, you can also use the oninput event, which is triggered when you type into an input box.
And remember, always check on the server as well. Javascript may fail or can be deliberately disabled. Your server should always perform necessary checks. Although I believe that MySQL will automatically truncate texts that are too large...
A good alternative would be to set the maxlength property of the inputs. This way, the maximum length is enforced even without javascript. Then, you can remove that flag and add the necessary events from javascript. This way, you will have a usable solution for javascript browsers, while having a more strict check for non-javascript browsers, which I think is better than no check at all.
I found the bug in your suggestion. Here my test patterns:
If limit max characters are 05 characters.
Test value: 123456, ABCDEF
1: Use keyboard, type the text normally
for 123456, 6 will be deleted
for ABCDEF, F will be deleted
Result: OK
2: Use keyboard, copy and paste 123456 and ABCDEF from other place
for 123456, paste (Ctrl V): "123456123456" => 456123456 will be deleted
for ABCDEF, paste (Ctrl V): "ABCDEFABCDEF" => DEFABCDEF will be deleted
Result: OK
3: Use mouse, copy and paste 123456 and ABCDEF from other place
for 123456, paste (Right click + paste): "123456123456" => NO characters will be deleted
for ABCDEF, paste (Right click + paste): "ABCDEFABCDEF" => NO characters will be deleted
Result: FALSE;
4: Use mouse, copy and paste 123456 and ABCDEF from other place after that type something else
for 123456, paste (Right click + paste): "123456123456" => NO characters will be deleted, type "123" using keyboard => All text will be deleted.
for ABCDEF, paste (Right click + paste): "ABCDEFABCDEF" => NO characters will be deleted, type "ABC" using keyboard => All text will be deleted.
Result: FALSE;
I give you my false from my project at same function. In my function this pattern are false for ALL. Here my : jsfiddle This function that I have found in the internet, sorry I forget the source so If you are the owner, please for give me to public here.
HTML:
//Count content
maxL = 2000;
var bName = navigator.appName;
function taLimit(taObj) {
if (taObj.value.length == maxL) return false;
return true;
}
function taCount(taObj, Cnt) {
objCnt = createObject(Cnt);
objVal = taObj.value;
if (objVal.length > maxL) objVal = objVal.substring(0, maxL);
if (objCnt) {
if (bName == "Netscape") {
objCnt.textContent = maxL - objVal.length;
} else {
objCnt.innerText = maxL - objVal.length;
}
}
return true;
}
function createObject(objId) {
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
} //End Count content
You have <b><label id="myCounter">2000</label></b> characters left
<br/>
<textarea class="inputtextfield" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')" id="content" name="content" rows=7 wrap="physical" cols=40></textarea>
I am very confused how to fix my bug.
There are two functions because there are two different events. If you wanted to know when someone pressed Ctrl + Enter for instance you need to know exactly when each key is hold down and when it is released.
In your case (display a warning when reached the limit) i would use keydown because that is what happens first, that way you know right at the moment when the user went over X characters. If you used keyup te user could press a key for several seconds without seeing any message.
To count the characters you can do:
document.getElementById("myInput").value.length

Categories

Resources