Keyup prevent default not working angular6 - javascript

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.

Related

keyup event does not set event shiftKey JAVASCRIPT

The function onkeyup works fine with all the characters when both SHIFT key and character are pressed , or keeping SHIFT key pressed and key up the character, but my problem happens when key up the SHIFT key before the character . The value returned is with lowercase characters . So for example if I key up SHIFT and press a, 'a' is returned but not 'A' .
So my question is how do to SHIFT key is being keyup . I've tried the following check but this didn't work :
pass_input_obj[i]['input'].onkeyup = function(event) {`enter code here`
if(event.key == "Process") {
if(event.code.includes("Shift")) keypressed= "Shift";
} else
keypressed= event.key;
if(keypressed == "Shift" || (event.code && event.code.includes("Shift"))) shiftclicked = false;
if(!isSpecialKey(keypressed) && !crtlclicked){
Capletter = keypressed;
if(shiftclicked == true){
Capletter = keypressed.toUpperCase();
}
}
Not sure if I got clear all your needs. I assume you want to press and release 'Shift' button and click any other character. That character then should be capitalized.
Here is my way of implementing it
var inputEl = document.getElementById('txt');
var isPrevShiftClicked = false;
inputEl.onkeyup = function(event) {
if(isPrevShiftClicked) {
inputEl.value = inputEl.value.slice(0, inputEl.value.length - 1) + inputEl.value.charAt([inputEl.value.length - 1]).toUpperCase();
}
isPrevShiftClicked = event.keyCode === 16;
}
<input type="text" id="txt" />

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

Replacing if the first number is a zero and the number is greater than 2 places

I have a calculator I'm working on and came across a problem. To combat so that users can't leave a field blank, I'm forcing a zero if the field is left empty. That's all fine, but the problem is that when the text in the field is deleted to remove the zero and enter a new number, it automatically enters zero so my new number looks like this: 05
How do i run a replace where if there is more than 2 places in the number and the first number is zero, replace the zero? Here's the code i'm using for my calculator.
$(function(){
calculate();
$('.input').keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
$('.input').on('keyup',function(){
if($(this).val()==''){
$(this).val('0');
}
calculate();
});
});
function calculate(){
var d6 = parseFloat(($('#d6').val()).replace(/,/g,''));
var d20 = parseFloat(($('#d20').val()).replace(/,/g,''));
var b20 = d6;
var e20 = parseFloat(($('#e20').val()).replace(/,/g,''));
var f20 = d20*e20;
var f22 = b20/f20;
var f23 = (52-f22)*f20;
$('#f20').html(formatCurrency(f20));
$('#f22').html(f22.toFixed(2));
$('#f23').html(formatCurrency(f23));
}
function formatCurrency(x) {
return '$'+x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
If you are essentially trying to turn it into a formatted number you could try type coercion:
'' + new Number('') // "0"
'' + new Number('0') // "0"
'' + new Number('05') // "5"
'' + new Number('0000.2') // "0.2"
Change the zeroing code to use the blur() event, i.e when the field loses focus.
$('.input').blur(function(){
if($(this).val()=='')
{
$(this).val('0');
}
});
I'm assuming that the text is removed from pressing the backspace key.
If that is the case then you keyup handler would fire when you backspace on the zero, which would detect no input, then add the zero.
First of all, you are doing it a hard way. And try this... if the user clicks on the input then it will be cleared and the user can write whatever number he wants...
$( ".input" ).focus(function() {
(this).val('');
});
In case you are using an HTML5 form you can avoid that piece of code like this:
<input type="number" placeholder="Type a number" required>
The required attribute is a boolean attribute.
When present, it specifies that an input field must be filled out.
Instead of using keyup and keypress event for checking and replacing blank to zero, use change event.
$(function(){
calculate();
$('.input').keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
$('.input').on('keyup',function(){
calculate();
});
$('.input').on('change',function(){
if($(this).val()==''){
$(this).val('0');
}
});
});
function calculate(){
var d6Val = ($('#d6').val() !== "")? $('#d6').val() : '0';
var d20Val = ($('#d20').val() !== "")? $('#d20').val() : '0';
var e20Val = ($('#e20').val() !== "")? $('#e20').val() : '0';
var d6 = parseFloat((d6Val).replace(/,/g,''));
var d20 = parseFloat((d20Val).replace(/,/g,''));
var b20 = d6;
var e20 = parseFloat((e20Val).replace(/,/g,''));
var f20 = d20*e20;
var f22 = b20/f20;
var f23 = (52-f22)*f20;
$('#f20').html(formatCurrency(f20));
$('#f22').html(f22.toFixed(2));
$('#f23').html(formatCurrency(f23));
}
function formatCurrency(x) {
return '$'+x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
One more thing. Change event only fires when you focus-out from that input.
Please let me know if you will face any issue.

validate input type="number"

I try to do some programming:
I have this order form with different input fields (name, amountOfProductA, amountOfProductB, amountOfProduct...) and I submit this form, after some validation, with a jquery script.
I plan to reuse the code and the number of product fields may vary form time to time.
In the validation I make sure that at least one of the (type="number") product input fields is filled in.
If a user types a number in one of the product inputfields and by mistake a character (or a number and a character) in the other the form submits with this later field empty.
Because the wrong filled in field submits empty I cannot validate this.
Can you please give me a clue how validate this?
Should I just juse type="text" input fields? (How do I check if at least one product field is filled in then?)
This is my code:
jQuery(function ($) {
$('#bttn-submit').click(function () {
$('input').css('background', '#fff'); // reset BGcolor
var formOk = true;
var allProdFields = $('input[type=number]') // Selection of all Product('number') fields
var numberOfProdFields = allProdFields.length; // How many ('number') fields are there?
// How many product fields are empty?
var prodFieldsEmpty = 0;
for (i = 0; i < numberOfProdFields; i++) {
if( $(allProdFields[i]).val() == '' || $(allProdFields[i]).val() == 0){
prodFieldsEmpty++;
}
}
// Is there at least one product field filled?
if(prodFieldsEmpty == numberOfProdFields){
var formOk = false;
alert('Form not OK');
allProdFields.css('background', '#f30302');
}
// Is the name field filled?
if( $('#pesoonNaam').val() == '') {
$('#pesoonNaam').css('background', '#f30302');
var formOk = false;
}
if( formOk == true ) {
document.actieForm.submit();
}
})
})
The code below will not let the user enter character in your field only number. Because the type="number" is html5 and doesn't work in all the browsers.
$(document).on('keydown', '.numeric-input', function(event) {
var dot_split = $(this).val().split('.');
if ($.inArray(event.keyCode,[46,8,9,27,13]) !== -1 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39) && dot_split.length <= 2) {
// let it happen, don't do anything
return;
}else{
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
})
Then you can check with an .each if any of the fields is empty.
prodFieldsEmpty = 0;
$('.numeric-input').each(function(){
if($(this).val() != ""){
prodFieldsEmpty++;
}
})
I hope this helps you!
You can try smth like:
function checkInputs(){
result = false;
$('input[type="number"]').each(function(){
if($(this).val() != '' && isNumeric($(this).val())) result = true;
})
return result;
}
UPD: Fiddle
You should not attach validation to the submit button as the user can submit the form without pressing it, attach validation to the form's submit handler:
jQuery(function ($) {
$('#formID').submit(
...
jQuery has an each method for iterating, so:
$('input[type=number]').each( function(index) {
/* do validation */
});
Within each, the function's this is set to the current element, so you can do:
if (this.value == 0) {
prodFieldsEmpty++;
}
The value of a form control is always a string, so the test this.value == 0 will return true if the value is '0' or '' (empty string). If you don't like using type coercion, then do:
if (this.value === '0' || this.value === '') {
If you want to check that the value is an integer, then there are any number of answers here about that, the simplest is probably the accepted answer here:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Note that this will allow all types of numbers, e.g. 2.34e3. If you just want to allow say positive integers, you can try:
function isPositiveInt(n) {
return /^\d+$/.test(n); // or return !/\D/.test(n)
}
Again, there are many ways to approach that.
Rather than count the number of fields and then the number that pass, if you only want to check that at least one passed, set a flag:
var passNumeric = false;
$('input[type=number]').each( function(index) {
if (isNumber(this.value)) {
passNumeric = true;
} else {
// do something with fails?
}
});
You can use the else branch to do something with the fails (or nothing).

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.

Categories