http://jsbin.com/cunejafehe/edit?html,js,console,output
var reg = /^[a-zA-Z\d\s\-'#(),"]*$/;
function myFunction(e){
console.log(e.value);
if(reg.test(e.value))
{
return false;
}
}
<input onkeyup="myFunction(this)" type="text">
I wonder why above code doesn't work, what I want to do is allow only these character to be in the input : a-z and 1-9 including 0, and these character -'#(),"
Please have a look at this approach. Here i am passing an event object instead of DOM element reference and then we are checking it against Regx expression.
var reg = /^[a-zA-Z\d\s\-'#(),"0-9]*$/
function myFunction(e){
var c = String.fromCharCode(e.which)
console.log(c);
if(reg.test(c))
{
return true;
}
else
return false;
}
$(document).ready(function(){
$( "#mytextbox" ).keypress(function( e) {
return myFunction(e);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Inline function : <input onkeypress="return myFunction(event)" type="text">
<br/>
Binding a function : <input id="mytextbox" type="text">
The test method belongs to a RegExp object, since you're not using that you should change reg.test(c) to c.match(reg) inside myFunction.
Moreover you are working on the full value of the field by passing this. I guess you can do something like this, even if not very elegant:
var reg = /^[a-zA-Z\d\s\-'#(),"]*$/;
function myFunction(e){
if (!e.value.match(reg)) {
e.value = e.value.slice(0, -1);
}
}
<input onkeyup="myFunction(this)" type="text">
Related
I have a JavaScript function to Validate only decimal value.I use the JavaScript onkeyup event.
function onlyNumeric(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
var exclusions = [8, 46];
if (exclusions.indexOf(key) > -1) {
return;
}
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
return false;
}
return true;
}
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">
It's working fine when I put value not from the number pad. But when I put value by number pad it's not working. So how can i fixed it?
Also I need fix it at two decimal point. But how can I do it?
Is onkeyup event Ok for this purpose?
Below is the code to help you out:
function onlyNumeric(evt) {
var pattern = /^\d{0,4}(\.\d{0,2})?$/i;
var element = document.getElementById("ColumnName");
if(pattern.test(element.value)) {
console.log("Vadid number:" + element.value);
} else {
console.log("Invadid number:" + element.value);
}
}
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">
You can use this Regex pattern :
/^\d+(?:\.\d{1,2})?$/
Explanation :
\d match a digit...
+ one or more times
( begin group...
?: but do not capture anything
\. match literal dot
\d match a digit...
{1,2} one or two times
) end group
? make the entire group optional
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">
<script>
function onlyNumeric(evt) {
var rx = /^\d+(?:\.\d{1,2})?$/;
var ele = document.getElementById("ColumnName");
if(rx.test(ele.value)) {
console.log("true");
}else{
console.log("false");
}
}
</script>
Another solution using addEventListener() instead of onkeyup:
<input type="text" class="form-control" id="ColumnName" name="ColumnName">
<script>
function onlyNumeric(evt) {
var rx = /^\d+(?:\.\d{1,2})?$/;
var ele = document.getElementById("ColumnName");
if(rx.test(ele.value)) {
console.log("true");
}else{
console.log("false");
}
}
var el = document.getElementById("ColumnName");
el.addEventListener("input", onlyNumeric, false);
</script>
Use this jquery plugin it validate decimal behaviour while typing and mouse click
https://github.com/sarkfoundation/Decimal-Behavior
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type='text/javascript' src="https://rawgit.com/sarkfoundation/Decimal-Behavior/master/sark-decimal/sark-decimal.js"></script>
<input type="text" data-behaviour="decimal">
I'm trying to prevent user from entering anything except numbers and letters, but my code doesn't even allow them itself. What could be the reason? Here's my code snippet:
$(document).ready(function(){
$("#txtuname").keypress(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
JSFiddle
$(document).ready(function () {
$("#txtuname").keypress(function (e) {
var validExp = /^[0-9a-z]+$/gi;
if (validExp.test(e.key)) {
$("#errmsg").html("");
return true;
}
else {
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
You can use keyup not keypress
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You can substitute input event for keypress event; adjust RegExp to /[0-9a-z]/i, use .split() with parameter "", Array.prototype.every(), RegExp.prototype.test() to check each character of input value at if condition; if each character is a digit or a letter condition is true, else false replace invalid characters of value using .replace() with RegExp /[^0-9a-z]/ig
$(document).ready(function() {
var validExp = /[0-9a-z]/i;
$("#txtuname").on("input", function(e) {
var val = this.value;
var check = val.split("").every(function(value) {
return validExp.test(value)
});
if (check) {
$("#errmsg").html("");
return check;
} else {
this.value = val.replace(/[^0-9a-z]/ig, "");
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You issue is you are not getting the value of the key that is being pressed. If you set the val variable like so, it will work as expected.
var val = String.fromCharCode(e.keyCode)
This gets the ASCII code of the key pressed, and then converting to the letter or number it represents. Then you can check against your regex.
This is because keypress events are fired before the new character is added to the value of the element (so the first keypress event is fired before the first character is added, while the value is still empty). You should use keyup instead, which is fired after the character has been added reference.
Here is the code
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
js
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(validExp.test(val))
{
$("#errmsg").html("");
return true;
}
else
{
// fix the value of input field here
$(this).val("");
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You need to use keyup so that the character is "added" already to the value if you're going to use this given technique.
Since String.prototype.match actually returns an array of the match, it won't work in the way you want it to. Not to mention that it is much more expensive than RegEx.prototype.test.
Bonus
You can use the technique of finding carret position in an input field shown in Get cursor position (in characters) within a text Input field
To actually fix the input field on keyup.
I am trying to create a simple web application. Like in Facebook chat when I enter "(Y)" it turns into the thumbs up icon. Similarly I am trying to do something like that with the following code. But it is not working for me. I am not expert with JavaScript. I need some help that what's wrong with the code?
And I made the code in a way that if i enter "y" it will return LIKE. I want to know how to show an icon after "y" input.
<html>
<head>
<title>Emogic</title>
</head>
<body>
<input type="text" id="input">
<input onclick="appear()" type="submit">
<p id="output"></p>
<script>
function appear(){
var value = document.getElementByid("input").value
var result = document.getElementById("output").innerHTML
if(value == "y"){
result = "LIKE"
}
else if(value == ""){
alert("You must enter a valid character.");
}
else{
alert("Character not recognised.");
}
}
</script>
</body>
</html>
There are a few issues/typo in your code :
it's document.getElementById(), with a capital I in Id.
result will be a string, containing the innerHTML of your element, but not a pointer to this innerHTML : when you then set result to an other value, it won't change the element's innerHTML as you expected. So you need to create a pointer to the element, and then set its innerHTML from the pointer.
The quick fix of your code would then be :
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
if (value == "y") {
output.innerHTML = "LIKE";
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="y">
<input onclick="appear()" type="submit">
<p id="output"></p>
But you'll find out that your user will have to enter exactly "y" and only "y" for it to work.
I think you should use instead String.replace() method with a regular expression to get all occurences of a pattern, i.e, for "(Y)" it could be
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
// The Regular Expression we're after
var reg = /\(Y\)/g;
// your replacement string
var replacement = 'LIKE';
// if we found one or more times the pattern
if (value.match(reg).length > 0) {
output.innerHTML = value.replace(reg, replacement);
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="I (Y) it (Y) that">
<input onclick="appear()" type="submit">
<p id="output"></p>
i have code that can be use for subtract and additional textbox values using javascript and it is working but problem is that javascript again and again executed function whenever onfocus textbox i want only one time javascript should be executed function?
javascript function again and again additional onMouseOver="return B(0);"
javascript function again and again subtraction onfocus="return C();"
javascript function again and again additional onfocus="return D();"
function getObj(objID){
return document.getElementById(objID);
}
function B(){
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
}
function C() {
getObj("balance").value=parseFloat(getObj("total").value || 0)-
(parseFloat(getObj("advance").value || 0)) ;
getObj("balance").value=parseFloat(getObj("balance").value || 0)-
(parseFloat(getObj("discount").value)||0) ;
return false;
}
function D() {
getObj("total").value=parseFloat(getObj("total").value || 0)+
(parseFloat(getObj("openbal").value || 0)) ;
return false;
}
Opening Balance:<input class="input_field2"
type="text" name="openbal" id="openbal"><br />
Total:<input class="input_field2" type="text"
readonly name="total" id="total" value="5000"><br />
Advance:<input class="input_field2" type="text"
readonly name="advance" id="advance" value="500"
onMouseOver="return B(0);"><br />
Balance:<input class="input_field2" readonly type="text"
name="balance" id="balance" onfocus="return C();"><br />
Rem Amount:<input class="input_field2" type="text"
name="recamt" id="recamt"><br />
Discount: <input class="input_field2"
style="background-color:#FFF !important;"
type="text" name="discount" id="discount" >
You could have:
var executedAlready = false;
An inside functions B and C have:
if(executedAlready != true){ executedAlready = true; }
else { return; }
Or maybe you could detach the events instead? I guess there are a few different ways to do this.
What the other answers tell you that the "quickest" way to get results is to make your functions only execute once.
You can do that like this:
Make a flag (just a variable that knows if your function has been triggered already).
When executing your functions, first check on this flag.
Here's an example how to do it with function B():
(Note: I didn't change your function, don't wanna get into that now)
// setup fired as false
var hasBFired = false;
function B(){
// if B is true, we do nothing
if (hasBFired) {
return;
// else if it is not true, basically only the first time you call this, flip the flag and execute the rest of the code.
} else {
hasBFired = true;
}
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
Now, repeat the same with C and D functions (setup two more flags).
This is not the best way - it's not good to setup global objects and stuff, but since you probably aren't getting any side library in, it will help you solve your issue for now. For long term solution, you should use an Event library (like YUI Event) and have it handle attaching and detaching actions to onfocus events for you.
you can use one or more flag(s) :
in the begenning of the page :
<script>
var flag = false;
</script>
and on your element:
<div .... onMouseOver="if(!flag) { flag = true; return B(0);}" > .... </div>
same for onFocus...
Question:
<body onload="setBlurFocus()">
<form method="POST" action="#">
<input id="id_username" type="text" name="username" maxlength="100" />
<input type="text" name="email" id="id_email" />
<input type="password" name="password" id="id_password" />
</form>
</body>
I wrote :
function setBlurFocus () {
var user_input = document.getElementById('id_username');
var email = document.getElementById('id_email');
var password = document.getElementById('id_password');
user_input.onblur = userSetBlur();
email.onblur = emailSetBlur();
password.onblur = passSetBlur();
user_input.onfocus = function() {
document.getElementById('id_username').value = ''
}
email.onfocus = function() {
document.getElementById('id_email').value = ''
}
password.onfocus = function() {
document.getElementById('id_password').value = ''
}
}
function userSetBlur() {
document.getElementById('id_username').value = 'Username'
}
function emailSetBlur() {
document.getElementById('id_email').value = 'Email'
}
function passSetBlur() {
document.getElementById('id_password').value = 'Password'
}
Question?
How to generalize or optimized this code?
You can always attach the methods in JavaScript:
function setBlurFocus() {
var user_input = document.getElementById('id_username');
user_input.onblur = someFunction;
// or with an anonymous function:
user_input.onfocus = function() {
// do something
}
}
Read more about traditional event handling and events in general.
Further explanation:
You attached the function setBlurFocus to the load event of the document. This is correct if you have to access DOM elements with JavaScript. The load event is fired when all the elements are created.
If you attach the setBlurFocus() to the blur event of the input field, then the function is only executed when the text box looses focus.
From your question I concluded you don't want set the event handlers in the HTML, but you want to set them form inside the setBlurFocus function.
Regarding your update:
This is wrong:
user_input.onblur = userSetBlur();
This assigns the return value of the function to onblur. You want to assign the function itself, so you have to write:
user_input.onblur = userSetBlur;
The () calls the function. You don't want that (in most cases, there are exceptions, see below).
Furthermore, you don't have to use named functions for onblur and anonymous functions for onfocus. It was just an example, to show you the different possibilities you have. E.g. if you assign an event handler to only one element, then there is no need to define it as extra function. But you have to do this if you want to reuse event handlers.
Here is an improved version:
function setBlurFocus () {
var values = ["Username", "Email", "Password"];
var elements = [
document.getElementById('id_username'),
document.getElementById('id_email'),
document.getElementById('id_password')
];
for(var i = elements.length; i--; ) {
elements[i].onblur = setValue(values[i]);
elements[i].onfocus = emptyValue;
}
}
function setValue(defaultValue) {
return function(){this.value = defaultValue;};
}
function emptyValue() {
this.value = '';
}
this inside the event handlers refers to the element the handler is bound to.
Note: Here setValue returns a function, that is why we call setValue in this case (and not just assign it).
Important note: This will also reset the values to Username etc, if the user entered some data. You have to make sure, that you only reset it if the user has not entered data. Something like:
function setValue(defaultValue) {
return function(){
if(this.value !== "") {
this.value = defaultValue;
}
};
}
and you'd have to define emptyValue similar:
function emptyValue(defaultValue) {
return function(){
if(this.value === defaultValue) {
this.value = "";
}
};
}
Now that I know what you actually want to do, have also a look at HTML5's placeholder attribute.
Well you've tagged it with jquery so this is how to do it in jquery:
function setBlurFocus () {
//do stuff here
}
$('#id_username').blur(setBlurFocus);
or
$('#id_username').blur(function(){
//do stuff here
});
Regarding your update
I using jquery as you tab jquery, the code was bellow , you can check a live sample with this link :
http://jsfiddle.net/e3test/zcGgz/
html code :
<form method="POST" action="#">
<input id="id_username" type="text" name="username" maxlength="100" />
<input type="text" name="email" id="id_email" />
<input type="password" name="password" id="id_password" />
</form>
javascript code :
$(function(){
var selector = {
username: $('#id_username'),
email: $('#id_email'),
password: $('#id_password')
};
for (var x in selector) {
selector[x].focus(function(){
$(this).val('');
}).blur(function(){
$(this).val($(this).attr('name'));
});
}
});
Hope it help.