I met some trouble with a javascript.
In fact I have in my database many records that are abreviations and ther equivalent,
for example, replace tel => telephone etc...
So I have this function
$('#tags').keyup(function(e){
var code = e.which ? e.which : e.keyCode;
console.log(code);
if (code == 'tel'){
var input = this.value;
input = input.substr(0, input.length -1);
console.log(input);
input += 'tel';
this.value = input;
}
});
Actualy this does not work the trouble is that I do not have aby mistakes
in the console of javascript.
Anykind of help will be much appreciated.
Kind regards.
SP.
This should work:
$('#tags').keyup(function(e){
var code = e.which ? e.which : e.keyCode;
var input = this.value;
if (input.indexOf('tel') != -1) {
this.value = this.value.replace(/\btel\b/gi,'telephone');
}
});
Here is a fiddle
When using keyup() the event handler only returns the keycode of the pressed key. For instance an x results in e = 88.
Use $("#tags").val() to get the value of the input element.
the keyCode or which property doesn't return a string, or even a single char. It returns the key code that represents the key that was struck by the client. If you want to get the corresponding char: String.fromCharCode(e.which || e.keyCode);.If the user hit on the a key, for example, the keycode will be 97, String.fromCharCode(97) returns a.
If you want to know weather or not the current value of the element contains the abreviation: tel, what you'll need to do is this:
$('#tags').keyup(function(e)
{
this.value = this.value.replace(/\btel\b/gi,'telephone');
});
This is untested and very likely to need some more work, but AFAIK, you want to replace all occurrences of tel by telephone. The expression I use /\btel\b/ replaces all substrings tel, provided they are preceded and followed by a word-boundary (to avoid replacing part of a word). Not that the end of a string and a dash are both considered to be word boundaries, too. If I wanted to type television, I'd end up typing telephoneevision. To avoid this, you'll need a slightly more complex expression. here's an example how you can avoid JS from treating a dash as a boundary, just work on it to take string-endings into account, too
Update
Perhaps this expression isn't quite as easy as I thought, so here's what I'd suggest you use:
this.value = this.value.replace(/(?:(\-?\b))tel(?:(\b\-?.))/gi,function(all,b1,b2)
{
if (b1 === '-' || b2.charAt(0) === '-')
{//dash, don't replace
return all;
}//replace
return b1 + 'telephone' + b2;
});
Input: I need a tel, quickly ==> I need a telephone, quickly
I need a tel ==> I need a tel (if the user is still typing, don't replace, he could be typing telescope, replace on submit or on blur)
I want to book a hostel for tonight ==> I want to book a hostel for tonight
Visit Tel-Aviv ==> Visit Tel-Aviv
When using keypress this way the code variable will contain the character code of the pressed character. Not the string of chars like the expected 'tel'. You could use onkeyup / onchange event and check the val() of the input element and use replace() to change the abbreviation to the intended string.
$('#tags').keyup(function(e){
var elem = $(this);
var input = elem.val();
// input = input.substr(0, input.length -1); // This might not be necessary
console.log(input);
// do the replacement
input = input.replace('tel','telephone');
elem.val(input);
}
});
Use replace method for replacing a word in string.
eg:
var str = "This is AIR";
var newstr = str.replace("AIR", "All India Radio");
console.log(newstr);
Related
I'm trying to use a regular expression to validate the input on a textbox
The expression should allow only numbers, maxmium two decimals, max one comma (,) and one minus symbol in front of the number (optional).
Valid:
0,25
10,2
-7000
-175,33
15555555555555,99
invalid:
9,999
15.03
77,77,77
etc
I'm using ^[-+]?[\d ]+(,\d{0,2})?$
The regex is used in a Jquery code to prevent the user from entering invalid numbers (event.preventDefault()):
$("input[name*='TB_mytbx']").on('keypress', function (event) {
var regex = new RegExp("^[-+]?[\d ]+(,\d{0,2})?$", "g");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Only a part of the regular expression seems to work.
It works with numbers (It does not allow me to enter letters) but it also won't allow commas (,) and the minus (-).
What am I doing wrong?
Edit
Before I used:
if (focused.val().indexOf(',') != -1) {
var number = (focused.val().split(','));
if (number[1] && number[1].length >= 2) {
event.preventDefault();
return;
}
But this gives annoying behavior. As soon as you enter a number with two digits you can't make edits anymore. For example: you can't change 200,50 to 300,50 or 100 300,50. (You get the point). I hoped that a regex could change that somehow.
I think you're massively over-complicating the regex. This should be plenty:
^-?\d+(,\d\d)?$
^ Start of line,
-? Optional minus sign,
\d+ Followed by a bunch of digits,
(,\d\d)? Followed by a comma and 2 digits, which are all 3 optional.
(alternative: (,\d{2})?)
$ End of line.
var regex = /^-?\d+(,\d\d)?$/;
console.log(regex.test('0,25'));
console.log(regex.test('-175,33'));
console.log(regex.test('15555555555555,99'));
console.log(regex.test('9,999'));
console.log(regex.test('15.03'));
console.log(regex.test('77,77,77'));
There you have a regex to validate the input value.
Now, that block of code can be replaced with this:
$("input[name*='TB_mytbx']").on('keypress', function (event) {
var regex = /^-?\d+(,\d\d)?$/;
var value = $(this).val(); // Use the field's value, instead of the pressed key.
if (!regex.test(value)) {
event.preventDefault();
return false;
}
});
For those of you who wanna know, I solved it using this code
$("input[name*='mythingy']").on('keypress', function (event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var value = this.value;
var value = value.replace(value.substring(theEvent.currentTarget.selectionStart, theEvent.currentTarget.selectionEnd), "");
value = [value.slice(0, theEvent.currentTarget.selectionStart), key, value.slice(theEvent.currentTarget.selectionStart)].join('');
var regex = /^[-+]?([\d ]+(,\d{0,2})?)?$/;
if (!regex.test(value)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
});
I've an input box in which I only want to allow 0-9, (, ), -, ., and (space) characters. After researching and picking up code from different tutorials, I managed to (I think) come up with the required regex pattern.
But it isn't working and always returning false even if the character typed is one from the above. The code that I've with me is as follows:
var regex = new RegExp("/[0-9.\(\)\b\ -]/", "gi");
if(regex.test(str)){
return true;
} else {
console.log('failed');
return false;
}
I'm having failed printed in the console every single time. What am I missing here?
EDIT: Demo (It seems to be working here)
EDIT2: JSFIDDLE
UPDATE:
I think my question is being misinterpreted here. I probably didn't do a good job at describing my use case. Well here it is then:
In my textbox, I only want to allow the above mentioned characters. So if a user types "23a" in the textbox, it should only allow "23" and "a" shouldn't be allowed to be typed
new RegExp() is superfluous here, just use regex literal notation (see note #2 below).
You want to anchor the expression to the beginning (^) and the end ($) of the string, to make sure it applies to the entire string. That's what you have tried to accomplish with g, but that is not what g does.
The i (case-insensitive) modifier is not necessary either, the pattern does not contain letters.
function isValidChar(str) {
return /^[0-9.() -]$/.test(str);
}
$(function(){
$('#p_zip').on('keypress', function (e) {
return isValidChar(String.fromCharCode(e.keyCode));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="p_zip">
Here is a version that works entirely without regex, comparing the keycode is enough.
function filterNumericKey(e) {
var c = e.keyCode;
return (c >= 48 && c <= 57) || // "0" .. "9"
c === 32 || // " "
c === 40 || // "("
c === 41 || // ")"
c === 45 || // "-"
c === 46; // "."
}
$(function(){
$('#p_zip').on('keypress', filterNumericKey);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="p_zip">
Notes
The following is an anti-pattern, in any language, not just JS:
if (booleanCondition) {
return true;
} else {
return false;
}
Just use return booleanCondition; directly instead.
If you want to use new RegExp() instead of a regex literal, you
must not use forward slashes to delimit your expression
must escape any backslashes, just like you would do in any other JavaScript string
Beware that both solutions will not check text that is pasted or dropped on the input element. You might want to write checks for that as well.
I managed to solve it. I was making a rookie mistake. I needed to return false on keypress event instead of keyup. And I was also taking the value of the textbox into account instead of the event object.
function isNumber(e) {
var theEvent = e || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
if (key.length == 0) return;
var regex = /^[0-9\.\b\(\) -]+$/;
if (!regex.test(key)) {
return false;
} else {
return true;
}
}
I have several inputs in a form, but what I want to achieve is to send only the ones who have at least 1 character (alphanumeric), but for those who have empty or whitespace values must not be sent.
The problem is that when a user sends a whitespace by mistake by pressing the spacebar it serializes a plus sign (+).
So far this is what I do to send serialized non-empty values.
//this will print a query string with the values, but for whitespaces it sends '+' signs.
$('#myform').find('input').not('[value=""]').serialize();
You can use $.trim:
$('#myform').find('input').filter(function() {
return $.trim(this.value) != "";
}).serialize();
This will also take the actual user input (.value property) not the .defaultValue (value attribute) like .not('[value=""]')
You can do following:
var obj = {};
$('#myform').find('input').each(function() {
var value = $(this).val().trim();
var inputName = $(this).attr('name');
if(value.length != 0) {
obj[inputName] = value;
}
});
$(obj).serialize();
By Googling this seems to work pretty fine:
$('#myform').find('input:filled').serialize(),
reference:
http://jqueryvalidation.org/filled-selector/
The following regex:
x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, "-");
adds dash after each 3rd character so entered 123456789 turns into 123-456-789.
Im trying to use this regex to format phone number. The problem arises on the 10th character. So entered 1234567890 turns into 1-234-567-890.
How would I modify the above regex to turn strings that have 10 digits into 123-456-7890. I use this regex because this happens as user is typing in uses keyup event.
If you know easier or better way of doing this please help me out, dashes has to be added while user is typing in. No other characters allowed.
Notes:
Cant use Jquery Masked input plugin (because if editing the middle character it's focus gets messed up)
How about
> "12345678".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-78"
> "123456789".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-789"
> "1234567890".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-7890"
If you ALREADY have the complete number or string
var x = "329193914";
console.log(x.replace(/(\d{3})(\d{3})(\d{3})/, "$1-$2-$3"));
If you WANT AS someone is typing...
$('#locAcct').keyup(function () {
var foo = $(this).val().split("-").join(""); // remove hyphens
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,3}', 'g')).join("-");
}
$(this).val(foo);
});
Do you need to use regular expressions for everything or would maybe something like this also help you out?
function convertToValidPhoneNumber(text) {
var result = [];
text = text.replace(/[^\d]/g,"");
while (text.length >= 6) {
result.push(text.substring(0, 3));
text = text.substring(3);
}
if(text.length > 0) result.push(text);
return result.join("-");
}
You could use this function everytime the text in your inputfield changes. It will produce the following results:
"12345678" -> "123-45678"
"123d456789" -> "123-456-789"
"123-4567-89" -> "123-456-789"
I believe the simplest way would be to add dash after every n digits would be like
var a = $('#result');
var x = "<p>asiija kasdjflaksd jflka asdkhflakjshdfk jasd flaksjdhfklasd f</p><p>12345678912345678912345678912312344545545456789</p>"
a.html(x.replace(/(\d{15})/g, "$1-"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>
Most easiest way is the following using simple javascript onkey and function... it will put dash hyphen after every 3 characters you input / type.
<input type="text" class="form-control" name="sector" id="sector" onkeyup="addDash(this)" required>
add the following script
<script>
function addDash (element) {
let ele = document.getElementById(element.id);
ele = ele.value.split('-').join(''); // Remove dash (-) if mistakenly entered.
let finalVal = ele.match(/.{1,3}/g).join('-');
document.getElementById(element.id).value = finalVal;
}
</script>
My regular expression which allows characters, numbers, dot and underscore is
var numericReg = /^[a-zA-Z0-9\._]+$/;
How could i allow backspace in this reg ex.?
You can use [\b] to match backspace. So, just add it to your character class: -
var numericReg = /^[a-zA-Z0-9._\b]+$/;
Note that you don't need to escape dot (.) in character class. It has not special meaning in there.
See also: -
http://www.regular-expressions.info/reference.html
for more escape sequences, and patterns in Regex.
I'd suggest you rewrite your regex to :
var numericReg = /^[a-zA-Z0-9._]+|[\b]+$/
Or:
var numericReg = /^(?:[a-zA-Z0-9._]|[\b])+$/
Check against 'event.keyCode' and 'value.length' before checking the regular expression.
Keycode 8 = backslash
$('#my-input').on('keypress change', function(event) {
// the value length without whitespaces:
var value_length = $(this).val().trim().length;
// check against minimum length and backspace
if (value_length > 1 && event.keyCode != 8) {
var regex = new RegExp('/^[a-zA-Z0-9\._]+$/');
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
}
The optimal solution for this problem is to check the value of textbox >0 before validating. This will help to solve error showing while pressing backspace in an empty textbox..!!
I also made a input type text that accept only numbers(non decimal) and backspace keyboard. I notice that putting [\b] in regular expression is not needed in non Firefox browser.
var regExpr = new RegExp("^[0-9,\b][0-9,\b]*$");