Will this code block $ % # or ( as I type?
var digitsOnly = /[0-9]/g;
var emailOnly = /[a-zA-Z0-9_.#-]/g;
var alphaOnly = /[a-zA-Z]/g;
var dateOnly = /[0-9\/]/g;
function restrictKeys(myfield, e, restrictionType) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if they pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if they are press other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
return true;
} else {
return false;
}
}
}
Will this code block $ % # or ( as I
type?
No. Detecting keys pressed is futile, users can paste or drag text into form controls so the key codes don't match the text being entered (or not fire a key event at all). Also, you only care about the value when the form is submitted, whatever value it has in the meantime is irrelevant to you.
Validate form control content on submit, restricting keyboard entry by any means is very, very annoying for users and easily bypassed.
Related
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" />
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 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).
Hi i need to achieve that breakline works here, because you can type enter, but after you type again no breaking line is given.
i make this fiddle http://jsfiddle.net/FPN9w/
Here is the JS code.
$(function () {
//you have to escaped the - character in a character class
var cleanRx = /[^a-zA-Z0-9 áéíóúÁÉÍÓÚÜüñѨ´,.¿?%&$!¡ªº#"()\-_\/]/g;
$('#title').keyup(function (e) {
var which = e.which;
//avoid useless replacements when <- and -> keys are pressed
if (which === 39 || which === 37) return;
this.value = this.value.replace(cleanRx, '');
}).trigger('keyup'); //perform replacement on initial content (remove if uneeded)
$('#description1').keyup(function (e) {
var which = e.which;
//avoid useless replacements when <- and -> keys are pressed
if (which === 39 || which === 37 || which === 13) return;
this.value = this.value.replace(cleanRx, '');
}).trigger('keyup'); //perform replacement on initial content (remove if uneeded)
});
add this code in js
$('#description1').keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
This is your updated JsFiddle http://jsfiddle.net/pratbhoir/FPN9w/3/
I tried to use this for a simple hotkey function, that reacts to keypress for some keys, but doesn't if your editing in the box with the given ID. Unfortunately now Hotkeys are disabled always. I get the alert() all the time :(
the textfield is on e.g. http://tyrant.40in.net/kg/news.php?id=160#comments
Inside the text area it works but my script does not recognize, whether I'm inside the text area or outside (it also doesn't help to click in textarea and click outside).
Please help me.
I also tried to do it another way by selecting (!$('#tfta_1 #search')) instead of $('html'), so that the hotkeys do not work wenn you are in of of these IDs. Unfortunately this did not work ether.
edit: the js also has tocheck if crtl, alt, shift to avoid interpret
// Hotkeys (listen to keyboard input)
$('html').keypress(
function(event){
// is cursor at the beginning / end of edit box
var textInput = document.getElementById("tfta_1"), val = textInput.value;
var isAtStart = false, isAtEnd = false;
if (typeof textInput.selectionStart == "number") {
// Non-IE browsers
isAtStart = (textInput.selectionStart == 0);
isAtEnd = (textInput.selectionEnd == val.length);
} else if (document.selection && document.selection.createRange) {
// IE branch
textInput.focus();
var selRange = document.selection.createRange();
var inputRange = textInput.createTextRange();
var inputSelRange = inputRange.duplicate();
inputSelRange.moveToBookmark(selRange.getBookmark());
isAtStart = inputSelRange.compareEndPoints("StartToStart", inputRange) == 0;
isAtEnd = inputSelRange.compareEndPoints("EndToEnd", inputRange) == 0;
}
// combine information -> is cursor in edit box?
var eb = isAtStart + isAtEnd;
// if in comment box
if ( eb ) {
// do nothing
alert('You are in the comment box');
}
// if key 'p' is pressed
else if (event.which == 112){
// open profile page
window.location = home + 'profile.php';
}
// if key 'q' is pressed
else if (event.which == 113){
// open quests overview
window.location = home + 'quests.php';
}
// if key 'r' is pressed
else if (event.which == 114){
// open raids overview
window.location = home + 'raids.php';
}
// if key 'f' is pressed
else if (event.which == 102){
// open fraction tracker
window.location = home + 'factiontracker.php';
}
}
);
You need to check the event.target property.
if ('textarea' == event.target.tagName.toLowerCase()) {
return;
}
Or:
if ($(event.target).is('textarea')) {
return;
}
As for the modifier keys, see event.shiftKey, event.ctrlKey and event.altKey.