Not allow initial spaces on input - javascript

I need to deny initial spaces on my input (which is not in a form), I have code like this:
<input id="customer-name" class="required no-spaces" minlength="3" />
And this is my javascript function:
$(".no-spaces").on('keypress', function(e) {
if (e.which == 32) {
return false;
}
});
But this doesn't allow spaces in any part of the input. How to do it just before any text?
Edit: The real is that I'm doing an autocomplete with the input and, If i allow initial spaces it will return all data.

Verify if the string is empty beforehand.
$(".no-spaces").on('keypress', function(e) {
if ($(this).val() == "" && e.which == 32) {
return false;
}
});
Also, check this in order to prevent the case where the user selects the entire text and then presses space and this to check if the cursor is indeed at the beggining of the input (Thanks to Barmar for mentioning this specific case)

Just simply check there is another character on textbox.
$(".no-spaces").on('keypress', function(e) {
if (e.which == 32 && ($this).val() == '') {
return false;
}
});
Edit
I hope it might be work.
$(".no-spaces").on('keypress', function(e) {
$(this).val(function(i, v) {
if (v[0] == ' ') {
return v.slice(1, v.length);
};
return v;
});
});

$(".no-spaces").on('keypress', function(e) {
if (e.which == 32) {
$(this).val($(this).val().replace(/^\W*/, ''));
}
});

This works for me.
$(".no-spaces").on('keypress', function(e) {
var val = $(this).val();
val_ltrim = ltrim(val);
$(this).val(val_ltrim);
});
Greetings.

Related

Removing a first space in input while focusing with space bar

When press spacebar it calls a function and that function focus a input tag and it already creates a space in that input and I don't want it. How do I remove that space ?
Here is what I have done..
<input type="text" class="user-answer" name="useranwer">
var userAnwer = document.querySelector('.user-answer');
window.addEventListener('keypress', myFun);
function myFun(e) {
if (e.keyCode === 32) {
userAnwer.focus();
}
}
You can use Event.preventDefault(). You also have to check the value to allow space afterwords.
var userAnswer = document.querySelector('.user-answer');
window.addEventListener('keypress', myFun);
function myFun(e) {
if(e.keyCode === 32 && (e.target.value == undefined || e.target.value == "")) {
e.preventDefault();
userAnswer.focus();
}
}
<input type="text" class="user-answer" name="useranswer">
You could prevent the default from happening which would be adding the space in this example.
function myFun(e) {
if(e.keyCode === 32 && userAnwer.value.length == 0) {
e.preventDefault();
userAnwer.focus();
}
}

Keyup prevent default not working angular6

I want to stop entering any number after validating a custom regular expression , the issue is condition got true but event.preventDefault is not preventing the input , The reg ex is to input value in percentage between 1-100 with decimals
/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/
this is my input
<input type='text' (keyup)="preventPercentage($event)" [(ngModel)]="value">
ts
preventPercentage(event){
var p = event.target.value
var s= p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null
if(!s && p){
event.preventDefault();
}
}
user can still enter any value even the condition is true
input anything between 100 above it still working and event is not preventing values
<input type='text' (keydown)="preventPercentage($event)" [(ngModel)]="value">
I used key down but it allows to enter 123 i.e three digit numbers
and I cannot then remove that number using backspace what exactly I am doing wrong can anyone suggest a sol any help will be appreciated
Try this. I think there is a change required in the regex as per your requirement.
preventPercentage(event){
var p = event.target.value + event.key;
var s = p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null;
if (!s && event.keyCode !== 8) {
event.stopPropagation();
return false;
}
}
Use this with keydown:
<input type='text' (keydown)="preventPercentage($event)" [(ngModel)]="value">
preventPercentage(event: any) {
function stopProgram() {
event.stopPropagation();
return false;
}
if (event.keyCode === 8) {
return true;
}
var p = event.target.value;
if ((event.keyCode === 190 && p.indexOf('.') > -1) || p === '100') {
return stopProgram();
}
p = p + event.key;
var s = p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null;
if (!s && event.keyCode !== 190) {
return stopProgram();
}
}
This is because it's necessary to use keydown event, not keyup.
It considers that the keyboard action is already done and you cannot cancel it.

prevent all characters and symbols if the first character is not # in jquery or javascript

I was trying to prevent all characters and symbols if the first character is not #(hash) in jquery or javascript.
This is what I have tried, but keyup did not work.
<input data-role="tagsinput" type='text' placeholder="Enter search tags..." id="searchtag">
$("#searchtag input").keyup(function () {
if ($(this).val().length >= 1){
if ($(this).val() !== "#"){
$(this).val('');
}
}
});
One option is to prevent every event on key down, therefore the event will not register and you will not need to remove a character that has been added.
NOTE: The if statement can be simplified, written this way for clarity purposes.
Try to run the following snippet:
const input = document.getElementById('searchtag');
input.addEventListener('keydown', function(e) {
if (e.key === '#' && this.value.length === 0) {
// Do nothing
} else if (this.value.length > 0 && this.value[0] === '#') {
// Do nothing
} else {
e.preventDefault();
}
});
<input type="text" id="searchtag">
Your selector is wrong. The input should come in front or shouldn't come. Use either of it:
$("input#searchtag").keyup(function() {
if ($(this).val().length >= 1) {
if ($(this).val() !== "#") {
$(this).val('');
}
}
});
$("#searchtag").keyup(function() {
if ($(this).val().length >= 1) {
if ($(this).val() !== "#") {
$(this).val('');
}
}
});
When you give a space and input, it will try to look for the child input under the element with id #searchtag.

Preventing user from typing text into a text box but allowing paste keyboard shortcut

I was wondering if there was a way to disable all key-down events (such as typing text) while the text box element is selected/has focus but still allow the ctrl+v paste shortcut to be used. In other words I'd like to make it so the only way a user can enter any text into the box is by pasting it (either by using the context menu or by the ctrl+v).
Try this simple solution:
<input type="text" id="txtbox" />
$(document).ready(function () {
var ctrlKey = 17
var vKey = 86
$("#txtbox").keydown(function (e) {
if (!(e.ctrlKey && e.which == vkey)) {
return false;
}
});
});
DEMO
Here's the code, deactivate keydown, but keep Ctrl+v working.
http://jsfiddle.net/70h3zron/
var ctrlActive = false;
$('#idtext').keydown(function(e) {
if(ctrlActive)
{
if(event.which == 86) {
return true;
}
else
{
e.preventDefault();
return false;
}
}
else
{
if(event.which == 17)
ctrlActive = true;
else
{
e.preventDefault();
return false;
}
}
});
$('#idtext').keyup(function(e) {
if(event.which == 17) {
ctrlActive = false;
}
});
Use this in jQuery,
$('#yourTextElementId').keypress(function(){
return false;
)};
Demo

How to find out user pressed "enter" in text input?

I'm trying to add text input's element to my array when user pressed enter key. but I don't know how to do that. I tried this if statements but they didn't work:
var val = $("#txbxfeeds").val();
if (val[val.length-1] == "\r") {
alert("HI");
}
if (val[val.length-1] == "\n") {
alert("HI");
}
How can I do this?
I can suggest the following:
var vals = [];
$("#txbxfeeds").on("keypress", function(e) {
if (e.which == 13) {
vals.push(this.value);
}
});
DEMO: http://jsfiddle.net/Q4CUf/
$("#txbxfeeds").on('keyup', function(e) {
//13 is the code for enter button
var val = $(this).val(); // or this.value
if(e.which == 13) {
alert( val );
}
});
Working sample
Read more about jQuery event.which

Categories