Removing a first space in input while focusing with space bar - javascript

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();
}
}

Related

How to move to next input field when enter key is pressed?

what to write after console.log('successful') so that i enter into next input field using id?
<script>
function invokeFunc() {
addEventListener('keydown', function(evt) {
var whichKey = checkKey(evt);
if (whichKey == 13) {
console.log('successful');
}
});
}
function checkKey(evt) {
console.log(evt.which);
return evt.which;
}
</script>
That should work:
if (whichKey == 13) {
console.log('successful');
evt.preventDefault(); // if it's inside <form> tag, you don't want to submit it
document.getElementById('nextInputID').focus();
}
my method will work if the input field is next each other like this
<input type="text">
<input type="text">
you can improve this by figuring out how to get the next input field when keycode is 13
in my case i use nextelementsibling and check if its an input (*you can add or logical || nextEl.nodeName === 'SELECT')
if nextElement is form field then focus() on it if not you done
document.querySelectorAll('input').forEach( el => {
console.log(el)
el.addEventListener('keydown', e => {
console.log(e.keyCode);
if(e.keyCode === 13) {
let nextEl = el.nextElementSibling;
console.log(nextEl)
if(nextEl.nodeName === 'INPUT') {
nextEl.focus();
}else {
alert('done');
}
}
})
})

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.

Not allow initial spaces on input

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.

jQuery keydown but ignore if in text box

I'm calling a function (below) that will perform an action if the user presses the delete button. It is working fine but I need to to only do it on the page and not when a user is typing (inside an input or inside a textarea).
$(window).keydown(function (evt) {
if (evt.which == 46) { // delete
goDoSomething();
}
});
Any ideas how I can amend the above to not fire if the user is in an input or textarea?
Thanks in advance,
Dave
check evt.target's type:
$(window).keydown(function (evt) {
if (evt.target.tagName.toLowerCase() !== 'input' &&
evt.target.tagName.toLowerCase() !== 'textarea' && evt.which == 46) { // delete
goDoSomething();
}
});
You could have a global variable and set it to something when a textbox is focussed on and reset it on blur. Something like this:
var textboxSelected = false;
$(":input").focus(function () {
textboxSelected = true;
});
$(":input").blur(function () {
textboxSelected = false;
});
Then in your onKeyDown event check whether the variable is set to false before carrying out the rest of the functionality:
$(window).keydown(function (evt) {
if (evt.which == 46 && textboxSelected == false) {
goDoSomething();
}
});
try sometihing like this:
$(window).keydown(function (evt) {
if(evt.target != $('input') && evt.target != $('textarea')){
if (evt.which == 46) { // delete
goDoSomething();
}
}
});

Categories