regex to replace non numeric - javascript

I want to replace all my non numeric characters with an empty string. I found this solution
I am trying to replace the value of an input element on change. But when I use above, it is not replacing until I press a number.
Each non-digit I type stays until I type a digit
Ex: 2aaaaa will not be replaced. But as soon as 2aaaa3 is typed it will replace all the a's and it becomes 23
Is this the normal behaviour? How can I achieve my requirement.
component.ts
mobileChanged = () => {
this.mobile = this.mobile.replace(/\D/g,'');
};
angular component.html
<input type="text" [(ngModel)]="mobile" (ngModelChange)="mobileChanged()">

You can use keyup from jQuery or onkeyup from Javascript.
$("document").ready(function() {
$("input").keyup(function() {
let v = this.value.replace(/\D/g, '');
this.value = v;
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="" />

Yes, it's the usual behaviour for ngModelChange but seems you need onkeyup event here to replace Non-digits. Something like-
function mobileChanged() {
var txtinput = document.getElementById("fname");
var x = txtinput.value.replace(/\D/g,'');
txtinput.value = x;
}
<input id ="fname" type='text' onkeyup="mobileChanged()">
See if you still have confusion: https://stackoverflow.com/a/46403258/1138192

Related

How to input phone no in this 'xxx-xxx-xxxx' format in number input field

I want that whenever I type a number in the number input field in XXXXXXXXXX format it takes as XXX-XXX-XXXX using HTML, CSS and javascript.
Just like this snippet but without using the mask script.
$('.phone_us').mask('000-000-0000');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<input type="text" class="phone_us" />
There are some working answers here, but this solution is more stable.
Using the oninput event for instant replace and ...
Applying regex on the full string, to allow copy/paste, and finally ...
This code is shorter as well:
$('.phone_us').on('input', function() { //Using input event for instant effect
let text=$(this).val() //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
$(this).val(text); //Set the new text
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="phone_us" maxlength="12">
Or even without jQuery:
document.querySelector('.phone_us').addEventListener('input', function() { //Using input event for instant effect
let text=this.value //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
this.value=text; //Set the new text
});
<input class="phone_us" maxlength="12">
you could try like this
$(document).ready(function () {
$(".phone_us").keyup(function (e) {
var value = $(".phone_us").val();
if (e.key.match(/[0-9]/) == null) {
value = value.replace(e.key, "");
$(".phone_us").val(value);
return;
}
if (value.length == 3) {
$(".phone_us").val(value + "-")
}
if (value.length == 7) {
$(".phone_us").val(value + "-")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<form id="form1" runat="server">
<input type="text" maxlength="12" class="phone_us"/>
</form>
You can implement like this
document.getElementById('txtphone').addEventListener('blur', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});txtphone
<input type="text" class="phone_us" id="txtphone" placeholder = "(000) 000-0000"/>
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
Use HTML5 input type=tel to get phone number, and pattern attribute to specify any pattern.
[0-9]{3} represent the 0-9 numeric and 3 digits.
Then, add a hyphen (-), and use the numerics pattern again.
You can use own pattern and your country wise pattern like
[1-9]{4}-[1-9]{6} for the format 1234-567890.
Use the min-length and max-length in HTML5 to set limit.
Note that these patterns won't automatically add the hyphens, but will only allow correctly formatted input.
If you want get more patterns, search on web or see HTML5pattern.com
Pure javascript.
Enter 10 digits in the input field and click anywhere outside the input field.
var myTel = document.getElementById("tel");
myTel.addEventListener("blur", function() {
var str=myTel.value;
var pattern=/[0-9]{10}/;
if (pattern.test(str)) {
newstr=str.slice(0,3)+'-'+str.slice(3,6)+'-'+str.slice(6,10);
myTel.value=newstr;
}
else {
// bad
myTel.value='bad value: only 10 digits';
}
})
<form>
<input type="text" id="tel" name="tel" maxlength='10'>
</form>

Format input text to uppercase

I'm begginer and I would like to build an event that started on change of input. The text entered in the input would be automatically formatted as follows:
The first letter must always be uppercase;
All other letters must be lowercase.
function formating() {
var nameOfPerson = document.getElementById("nameOfPerson").textContent;
var nameOfPerson = nameOfPerson[0].toUpperCase() + (nameOfPerson - nameOfPerson[0]);
document.getElementById("nameOfPerson").textContent = nameOfPerson;
}
<input type="text" id="nameOfPerson" onchange="formatting()" placeholder="type your name">
Try this:
function formatting() {
var nameOfPerson = this.value;
if (nameOfPerson.length > 0) {
nameOfPerson = nameOfPerson[0].toUpperCase() + nameOfPerson.substr(1).toLowerCase();
this.value = nameOfPerson;
}
}
<input type="text" id="nameOfPerson" onchange="formatting.call(this)" placeholder="type your name">
If you want to do this using CSS, then this is the tricks:
<input type="text" id="nameOfPerson" placeholder="type your name" style="text-transform: capitalize;">
CSS text-trasform property can change your input text as capitalize, lowercase and uppercase.
A simple way to achieve this is:
nameOfPerson.charAt(0).toUpperCase() + nameOfPerson.substring(1);
When to do it?
Blur
You can do it when input looses focus(blur) event. This will allow user to input in any format and when he is done, then you apply your formatting.
function formatting() {
var nameOfPerson = this.value
this.value = nameOfPerson.charAt(0).toUpperCase() + nameOfPerson.substring(1).toLowerCase();
}
var input = document.getElementById("nameOfPerson");
input.addEventListener('blur', formatting)
<input type="text" id="nameOfPerson" placeholder="type your name">
Input
Or you can enforce formatting using input event. This will take care of typing and pasting actions.
function formatting() {
var nameOfPerson = this.value
this.value = nameOfPerson.charAt(0).toUpperCase() + nameOfPerson.substring(1).toLowerCase();
}
var input = document.getElementById("nameOfPerson");
input.addEventListener('input', formatting)
<input type="text" id="nameOfPerson" placeholder="type your name">
Pointers
Avoid binding handlers in HTML. Anyone can change DOM using dev tools and change behaviour of your page.
textContent as name suggest is used for text bindings and will return static text. Inputs have value binding and you should use .value
When you use onclange="formatting()", handler will not have context pointing to element and you will have to fetch it again and again and DOM queries are expensive. Using .addEventListener() will bind context and is preferred as you can add more than 1 handler.
In (nameOfPerson - nameOfPerson[0]), - operator will convert value to numeric value and would yield NaN. When dealing with strings, use string helper functions.

Javascript Replace onKeyUp event with a string

Im not very good at JavaScript and need a hand with what I think is an easy script. Basically I have an input box that when the user types in a key it will disappear and change to whatever string I have. I could only get the one letter to change, so that I have something to show what i mean. So whenever a user types a message it gets replaced with an "h", what I want though is to have "hello" typed out letter by letter and not just "h" all the time and not "hello" all at once.
Here is the code.
<form action=# name=f1 id=f1 onsubmit="return false">
<input type=text name=t1 id=t1 value="" size=25 style="width:300px;"
onkeypress="if(this.value.match(/\D/))"
onkeyup ="this.value=this.value.replace(/\D/g,'h')">
</form>
JUST EDITED AS IT IS GIVING JS ERROR HOPE YOU WONT MIND:Are you trying something like this:
function replaceString(el){
var sampleText = "hello".split("");
var value = "";
console.log(el)
el.value.split("").forEach(function(str, index){
value += sampleText[index%sampleText.length];
});
el.value = value;
}
<form action=# name=f1 id=f1 onsubmit="return false">
<input type=text name=t1 id=t1 value="" size=25 style="width:300px;"
onkeypress="if(this.value.match(/\D/));"
onkeyup ="replaceString(this);"/>
</form>
If you want to simulate typing text into the textbox then you will need to use a timeout. The following function should suffice:
function simulateTyping(str, el)
{
(function typeWriter(len)
{
var rand = Math.floor(Math.random() * (100)) + 150;
if (str.length <= len++)
{
el.value = str;
return;
}
el.value = str.substring(0,len);
if (el.value[el.value.length-1] != ' ')
el.focus();
setTimeout(
function()
{
typeWriter(len);
},
rand);
})(0);
}
You'll need to pass it two parameters : the string to type e.g. "hello" and the element into which to type the string. Here's a simple wrapper function:
function typeHello() {
var el = document.getElementById('t1');
var str = 'hello';
simulateTyping(str, el);
}
When you call the typeHello function it will find the element with the "t1" id and type the "hello" text.

How can I convert text typed in an input box to lower case?

I can't figure out how to convert the text typed into a text input box (txtQuestion) into all lower case, i.e. typing "input" or "INpUt" will be read the same and output the same result.
Use toLowerCase() function. Eg: "INPuT".toLowerCase();
exampleFunction = function(){
//First we get the value of input
var oldValue = document.getElementById('input').value;
//Second transform into lowered case
var loweredCase = oldValue.toLowerCase();
//Set the new value of input
document.getElementById('input').value = loweredCase;
}
<input id="input" type="text" onkeyup="exampleFunction()" />
You have to choose the events that you want to watch and then return to the input the same value but lowercase:
function InputLowerCaseCtrl(element, event) {
console.log(element.value)
return element.value = (element.value || '').toLowerCase();
};
InputLowerCaseCtrl.bindTo = ['blur'].join(' ');
document.addEventListener('DOMContentLoaded', function() {
var input = document.querySelector('.input-lowercase');
return input.addEventListener(InputLowerCaseCtrl.bindTo, InputLowerCaseCtrl.bind(this, input));
});
<input class="input-lowercase" type="text" />
You can convert any string input to lowercase using the String.prototype.toLowerCase function
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase
For you example with an input for txtQuestion.
var inputStringLowerCase = inputTxtQuestion.value.toLowerCase();
https://jsfiddle.net/fbkq2po4/

always want to keep first digit of my textfield as 0

hi guys i have a html form where i have a textfield which is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows that possible using javascript or jQuery or anything else.
Here is another way.
the onKeyUp might not be how you want it to work but at least you have some ideas
<script>
window.onload=function() {
document.getElementById('part2').focus();
}
</script>
<form onSubmit="this.realvalue.value='0'+document.getElementById('part2').value">
<input type="text" name="realvalue" value="">This can be hidden<br />
<input type="text" style="border-right:0; width:12px" value="0" readonly="readonly" size="1"><input type="text" id="part2" style="border-left:0; width:13px" size="1" maxsize="1"
onKeyUp="this.value=(this.value.length>1)?this.value.substring(-1):this.value">
<input type="submit">
You can use the event "keyup" triggered when the user enters text in the field:
$('#my-input').keyup(function() {
var theInputValue = $(this).val();
// Do whatever you want with the value (like check its length,
// append 0 at the beginning, tell the user not to change first
// character
//
// Set the real value
$(this).val(newValue);
});
You may be better off with a '0' as text in front of a textbox that can only accept a single digit and then prepend the '0' programmatically?
I wrote and tested this code, and works exactly as you expect:
$(function (){
$('#input_id').bind('input',function (){
var val = $(this).val();
var r = val.match(/^[0][0-9]$/g);
if (r !== null){
val = r[0];
if (val.length === 1){
val = '0' + val;
}
}else{
val = '0';
}
$(this).val(val);
});
});
And works for copy/paste too =]

Categories

Resources