Check for special characters - javascript

I want to prevent users inputing special characters ()&<>[]{}% in the many input and text areas of our website. Which is the best way ? Users use IE8, Firefox and Chrome. The name and id in the input and textarea is dynamic. I have no control over it.
So basically, I just want a function and use the onclick event to call it. I thought :input selector would do the work. Thanks.
Please take a look at JSFIDDLE
function spCheck ()
{var str = $('textarea').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('You have entered illegal characterss. Please remove them and try again.');
}}

Add class notSpecilChar to elements you want to check and on blur alert or keyup event.
$('.notSpecilChar').blur(function () {
if (/^[a-zA-Z0-9- ]*$/.test(this.value) === false) {
alert('You have entered illegal characterss. Please remove them and try again.');
}
});

Related

Does 'keypress' jQuery event fire before an inputs value is updated?

I have a keypress event listener on an input field to confirm a password. I want the button on the page to be disabled until the password and confirm-password fields have matching values. I am using the .keypress() jQuery function, but it seems to always be one character behind what I expect it to be?
Here is the code
$('#confirm').keypress(function() {
console.log('#confirm').val();
if($('#password').val() == $('#confirm').val()) {
$('button').removeProp('disabled');
console.log("yes");
} else {
console.log("no");
}
});
But when I inspect element and look at the console window on my page, the first time the event is fired it prints the form value as blank. Then when I enter a second character, it prints only the first, and when I type a third character it prints the first two, etc.
For example, if I put asd into the password field and begin typing the same into the confirm field the output will look like this:
<blank>
no
a
no
as
no
So at this point both password and confirm fields have "asd", but I need to enter an extra character before that is recognized and the "disabled" property is removed from the button.
I have tried using .change() instead of .keypress() but that doesn't fire until the input field loses focus, which is not what I want.
I want the button on the page to be disabled until the password and confirm-password fields have matching values
If this is your goal, you can add event listeners to both inputs that call a validation function:
$('#password').on("input", function() { validatePassword(); });
$('#confirm').on("input", function() { validatePassword(); });
function validatePassword() {
if($('#password').val() && $('#confirm').val() && $('#password').val() == $('#confirm').val()) {
$('button').prop('disabled', false);
} else {
$('button').prop('disabled', true);
}
}
It also may be worthwhile adding an ID to the button. Using 'button' would enable/disable all elements on the page.
Example: https://jsfiddle.net/doL4t9vv/1/
I had the same problem few months ago.
Try to use the keyup function from Jquery.
Keypress event is fired when you press the key, so the input is not fill yet.
Keyup event is fired when you release the key.
Can use input event and simplify this down to
var $passwords =$('#confirm, #password').on('input', function() {
var thisValue = this.value.trim();
// does this input have value and does it match other
var isValid = thisValue && thisValue === $passwords.not(this).val().trim();
// boolean used for disabled property
$('button').prop('disabled', !isValid);
});

How to stop my code putting tabs into my text boxes

I have this piece of jQuery to detect when the cursor is inside the text box. The idea is to highlight the table row that the text box appears is.
$(".text").on("focus", function() { //do something });
The problem is that this code seems to be registering the tab key inside the text box. The cursor will still move to the next text box when I hit the tab key. However it always insert a tab space into the box as well!!
This is most unexpected and I must admit i'm a little confused by it...
Any help on this matter would be brilliant, thank you.
It seems that the alert() you are sending in the focus event is interrupting things in a strange way. You can fix this by setting a brief timeout before sending the alert; that ensures that the alert is sent AFTER the text box receives focus and the tab input has been handled.
setTimeout(function() { alert("box selected"); }, 1);
http://jsfiddle.net/5cjbcy9o/2/
Give every row a tabindex like this
var i=2;
$('tr').each($(this).attr('tabindex',i++))
A previous answer has addressed listening to the tab key, by checking the keyCode to see if it matches 9. However, the width of a tab character differs (also reliant on personal preferences), although it is either two or four spaces commonly. Therefore, you can append that white space to the value of the input text when the tab keydown event is detected.
In the following code I have opted to use four white spaces:
$(function () {
$(".text").on("focus", function () {
console.log("box selected");
}).on("keydown", function(e) {
if ((e.keyCode || e.which) == 9) {
e.preventDefault();
$(this).val($(this).val() + " ");
}
});
});
See proof-of-concept fiddle here: http://jsfiddle.net/teddyrised/5cjbcy9o/1/

How can I tell when a character has been typed in an input field?

Let's say I have an input field with an id of code ( #code ).
How can I tell when a new character has been typed in it with javascript or jQuery ?
This is when the text is manually being entered or is done by javascript / jQuery.
Use Change function to track any changes in the textbox input. Change event will be triggered only if you focus out of the text box
$('#idoftextbox').change(function(){
//do something
});
If you want to detect as the user enters something then you need to use KeyPress
$('#idoftextbox').keypress(function(event) {
if ( event.which == 13 ) { //This will give you the key code
event.preventDefault();
}
});
Edit
In modern browsers only, you can use the "input" event. The change event will probably help you in most cases for all browsers and jQuery and JS examples are defined below.
As mentioned the change event will only fire on an input losing focus so you'd have to use a combination of techniques to cover all bases, including checking the field value at given intervals. A thorough explanation that covers all scenarios can be found on SO here:
Detecting input change in jQuery?
jQuery:
$('#code').on('change', function(e){
//do something
});
Javascript
document.getElementById('code').addEventListener('change', function(e){
//do something
});
This will trigger on every keypress.
Using Javascript:
document.getElementById('id').addEventListener('input',function(e){
console.log("Print Hello World");
//do something else
});

jquery autocomplete for keypress event

I create comment box like a facebook comment box. I have to do like this in textarea box type # sign and after I type letter then detect this letter or letters and popup friend list.
$("textarea#event_message").autocomplete("friendsAutoComplete");
this method used for autocomplete that works fine. but want this method fire after type # sign.
I tried this way
$('textarea#event_message').keypress(function(event) {
if(event.which == 64) {
$('textarea#event_message').autocomplete("friendsAutoComplete");
}
});
and I also tried jquery live method
It doesn't like work.How can I solve that problem?
First of all, what is the string "friendsAutoComplete" you referring?
To fire a search using an initialized autocomplete widget, you should call the search method instead.
http://jqueryui.com/demos/autocomplete/
So you may try out
$('textarea#event_message').keypress(function(event) {
if(event.which == 64) {
$('textarea#event_message').autocomplete("search");
}
});

Trigger an event when textbox contains specific keycode

I am currently working on a jQuery functionality to check a textbox for certain character values and then trigger some event depending on what character it is.
I figured the easiest way to process this would be by checking on keycodes. I have tried some different things to make the event trigger, but nothing seems to happen.
One of the things I want to check is if a textbox contains an # character (which is not allowed in the specific textbox, and it's keycode is 64 according to this site - expandinghead)
Some of the code I've attempted to use:
$("#NoEmailAllowed").live({
"keyup": function(e) {
if((e.keyCode == 64) || (e.which == 64))
{
$(this).addClass("redBg");
}
}
});
$("#NoEmailAllowed:contains('#')").live({
"keyup": function() {
$(this).addClass("redBg");
}
});
$("#NoEmailAllowed").keyup(function(){
if(this.val().contains("#"))
{
$(this).addClass("redBg");
}
});
I've tried a lot of others too, but they were quiet similar to the ones above.
So just to make everything clear about what I'm trying to achieve is:
When a user enters something in this textbox the jquery shall check for any # characters on-the-fly, and if it finds any # characters, trigger an event - for instance an alert or add a css class.
The keyup() event operates with scancodes, you're better off using keypress() to catch actual text entry (as mentioned in the jQuery documentation):
$(function(){
$('#NoEmailAllowed').keypress(function(e) {
if(e.which == 64)
{
$(this).addClass("redBg");
}
});
});
jQuery normalizes e.which, there is no need to check anything else.

Categories

Resources