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).
Related
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.
I want to allow typing Latin Characters but I don't want user can type Korean Hangul characters.
Please help me answer. Thank you in advance.
Based on this article,
https://en.wikipedia.org/wiki/Korean_language_and_computers
You would want to do something like this (untested):
$(document).on('keypress', 'input', function (e) {
var key = event.which || event.keyCode;
// Hangul Syllables
if (key >= 0xAC00 && key <= 0xD7A3) {
e.preventDefault();
}
// Hangul Jamo
if (key >= 0x1100 && key <= 0x11FF) {
e.preventDefault();
}
// Hangul Compatibility Jamo
if (key >= 0x3130 && key <= 0x318F) {
e.preventDefault();
}
// Hangul Jamo Extended-A
if (key >= 0xA960 && key <= 0xA97F) {
e.preventDefault();
}
// Hangul Jamo Extended-B
if (key >= 0xD7B0 && key <= 0xD7FF) {
e.preventDefault();
}
});
However, this would not stop anyone from copying/pasting Hangul characters into the input field, you would need to find something separate for that.
A more simplified way is to use form validation (this is a more simplified approach):
<input type="text" pattern="[^가-힣]+">
What you should do is instead be testing for the characters on the server side and returning a form error.
This question already has answers here:
How to limit typing number in text input
(4 answers)
Closed 4 years ago.
$(document).on('keyup keydown',function(key){
if(key.which >= 48 && key.which <= 57 && $('#sell').val() >= 9999 ) {
return false;
}
else {
if(key.which >= 48 && key.which <= 57 && $('#sell').val() <= 9999 ) {
return true;
}
}
});
Basically what I want to do is prevent someone from reaching higher than 9999 on an input.
But the problem is that if they type "55555" it would go through.
They couldn't type any higher than that and could delete it, but I don't want them to get higher than 9999.
Does anyone have a solution?
EDIT:
I need to somehow also prevent the input from working if it detects a higher number.
Try this:
var lastVal;
$("#sell").on('keydown', function(e){
if(e.which === 8){ // allow backspace
return;
} else if((e.which < 48 || e.which > 57) && (e.which < 96 || e.which > 105) ) { //only allow numbers & num pad numbers
return false;
}
if(e.target.value <= 9999) lastVal = e.target.value; //prevent key holding
});
$("#sell").on('keyup', function(e){
if(e.target.value > 9999){
e.target.value = lastVal;
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id=sell />
You could try something like this:
let sell = $('#sell');
let lastVal = 0;
sell.on('keyup keydown', function(key) {
let cc = key.which;
return (cc <= 57 && cc !== 32);
});
sell.on('input', function(evt) {
const newVal = sell.val();
if (newVal < 0 || newVal > 9999) {
sell.val(lastVal);
}
else {
lastVal = newVal;
}
});
Note that this only captures key events on the input itself, not the whole document. While this limits the user to typing digits (character below 48 (except space) are allowed because those are things like arrow keys and backspace), more work would be needed if you wanted to allow the user to perform actions like copy and paste.
The reason for not testing the val() of the input in the key event handler is a matter of timing: The key down event doesn't change the value of the input field, and the key up event comes after the value has been updated and it's too late to prevent the value change.
What this code does instead is let the value momentarily go out of range, but immediately reset it to the last valid value when that happens.
Plunker here: http://plnkr.co/edit/xsVQG1EzsDLMt8POCJUX?p=preview
Make the max length equal to 4 in HTML and use JS to force integer type, put max on input to prevent higher than 9999... Or do it manually for all of it . Up to you
With JS... on keydown: Strip non integers
if($("#inputID").val().length > 4){ KILL EXTRA LETTERS }
Once done.
If ($("#inputID").val() > 9999){ $("#inputID").val(9999); }
Remember, if this is for a form to validate the answer on the server side so the client can't override HTML and JS checks.
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.
I am trying to get it where, if there is value in the input, go ahead and do your thing but if there isn't, don't do anything. I keep getting getting it where, if there is nothing in the input, a failure message occurs but only if I hit the enter key
jsfiddle.net/BBaughn/8ovrmhgp click the space in the lower right corner, then press enter. It shouldn't pop up, because the input is not focused.
login/failure jQuery:
$(document).ready(function(){
$('.btn1').on('click', function(){
var login = [marion, 'FATHER1'];
var marion = $('#logging').val();
marion = marion.toUpperCase();
if (marion !== 'FATHER1' && $('#logging').val()) {
alert('Login Failed');
} else if (marion === 'FATHER1' && $('#logging').val()) {
$('.notify').css('margin-top', '0');
$('#logging').val('');
}
});
$('.exit').on('click', function(){
$('.notify').slideUp('slow');
});
});
if you just want to check if an input is empty, I'm guessing #logging is the input:
$('.btn1').on('click', function(){
var marion = $('#logging').val();
if (marion == '') {
//this means the input value was empty
}
});
if the length is equal zero, that means the field is empty. It works after adding length === 0 check, please try this,
if (e.which == 13 && $('.btn1').val().length === 0) {
e.preventDefault();
} else if (e.which == 13 && $('.btn1').focus()) {
$('.btn1').click();
}
Ok, I think I get what you mean now. You're checking the entire document for keypresses as is, you need to check the input only. I think this is a good solution to do that:
$('.login input').keypress(function (e) {
if (e.which == 13 && !$('#logging').val()) {
e.PreventDefault();
} else if (e.which == 13 && $('.btn1').focus()) {
$('.btn1').click();
}
});
Working Fiddle here
$(document).ready(function(){
$('.btn1').on('click', function(){
var login = [marion, 'FATHER1'];
var marion = $('#logging').val();
marion = marion.toUpperCase();
if (marion !== 'FATHER1' && $('#logging').val()) {
alert('Login Failed');
} else if (marion === 'FATHER1' && $('#logging').val()) {
$('.notify').css('margin-top', '0');
$('#logging').val('');
}
});
$('.exit').on('click', function(){
$('.notify').slideUp('slow');
});
});
I didn't realize that my if statement was if the input wasn't detecting the right login, so it didn't matter if it was out of focus. Now it says "if it's not FATHER1 and there is value in the input only, then send this alert"