How to insert hyphen "-" after 4 digits automatically in TextBox in html5? - html

I have made validation in input field in html5 to get this format 03xx-xxxxxxx.
pattern="03\d{2}-\d{7}"
Now I want to add this hyphen symbol automatically after fourth digit.How to do that?

I must advice you against this type of input edit since it's usually frustrating when you need to edit typos.
Also I have no idea of the issues related to accessibility.
The input pattern only checks the data on submit, so it's not what you are looking for.
That said, here's one possible solution in JS:
// select the input element
var i = document.querySelector('input.hyphen');
// number of charatcers before the hyphen
var n = 4;
// run this function everytime the user release a key
i.addEventListener('keyup', function (event) {
// if there are more then n digits
if (i.value.length > n) {
// save the carret position
var s = i.selectionStart;
// remove all dashes
var t = i.value.replace(/-/g, '');
// beginning string with n digits
var b = t.substr(0, n);
// end string with what's left (maxLength)
var e = t.substr(n);
// join then with a dash
i.value = [b, e].join('-');
// if the caret was before the dash put it back to the saved position
if (s <= n) i.setSelectionRange(s, s);
// if the caret was next to the dash put it after
if (s == n+1) i.setSelectionRange(s+1, s+1);
}
});
<input class="hyphen" placeholder="0000-0000000" maxlength="12">

I have made validation in input field in html5 to get this format 03xx-xxxxxxx.
One alternative approach (without javascript) is to use three <input /> fields.
Working Example:
#country,
#region {
width: 16px;
}
#local {
width: 56px;
}
<input type="text" id="country" value="03" readonly />
<input type="text" id="region" pattern="[0-9]{2}" placeholder="88" />
-
<input type="text" id="local" pattern="[0-9]{7}" placeholder="8888888"/>

Related

How can I automatically insert commas when a user inputs currency value in an Angular 7 reactive form, no [(ngModel)]

I have an input field where the user can input a numeric value. I need to automatically insert commas after every 3rd digit. When the user deletes numbers, the commas need to be in the correct places (after every 3rd digit, starting from the first number) as well as stay in place instead of relocating to the end of the input value. I cannot use ngModel, this is a reactive form.
I have tried this method in my TS file, to mask the user input
maskInputAmount(e) {
const t = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})
(\d{0,3})/);
e.target.value = t[2] ? t[1] + ',' + t[2] + (t[3] ? ',' + t[3] : '') :
t[1];
}
And in my HTML input field
<input (input)="maskInputAmount($event)" maxlength=11
formControlName="businessNetWorth" id="businessNetWorth"
type="text" class="form-control col-3 col-lg-12" data-hint="yes">
I am having commas come after every 3rd number. However, when deleting numbers from the end of the input, the commas at the front of the number should update correctly. For example, I enter '123,456,789'. When I delete the last two numbers I get '123,456,7' when it should be '1,234,567'.
One other issue, when a user deletes one of the first numbers, the comma in the input box automatically repositions itself to the end of the input value, I need it to stay in place. For example: '123,456,789'. I delete '3' and have '124,567,89' and the cursor is now behind the '9' when it should stay in front of the '2'.
How can I change my maskInputAmount(e) method to make this behave correctly?
Following code worked for me. (Assume present currency is in Indian rupees. If you want to have your own currency then you need to mention your country's code in code).
app.component.html
<input type="text" [formControl]="currency" (input)="changeToCurrency(currencyTextRef)" #currencyTextRef>
//sending reference of input element #currencyTextRef to function
{{ currency.value }}
app.component.ts
currency = new FormControl();
temp;
currncyLength=0;
changeToCurrency(currencyTextRef) {
this.currncyLength = this.currency.value.length;
console.log("currency len is "+this.currncyLength);
let index:number;
// if(currencyTextRef.selectionStart || currencyTextRef.selectionStart == '0') {
// console.log("index isss "+currencyTextRef.selectionStart);
index = currencyTextRef.selectionStart; //getting caret(cursor) position
// }
console.log("index is "+index);
// console.log("value is "+this.currency.value);
let a = this.currency.value;
a = a.replace(/,/g,'');
let num:number = + a;
let temp = new Intl.NumberFormat('en-IN').format(num); //inplace of en-IN you can mention your country's code
// console.log("temp is "+temp);
this.currency.setValue(temp.toString());
console.log("pressent len iss "+this.currency.value.length)
if(this.currncyLength<this.currency.value.length) {
console.log("incoming to < ")
index+=1;
currencyTextRef.setSelectionRange(index,index);
}
else if(this.currncyLength >=this.currency.value.length) {
console.log("incoming to > ");
// index-=1;
currencyTextRef.setSelectionRange(index,index);
}
// else {
// currencyTextRef.setSelectionRange(index,index);
// }
}
Following link might help.
Intl number MDN

Link defines which checkbox is checked on redirect

Example here : http://webintegrator.edu.ats.dk/kean0012/smartgym/
(scroll to bottom and you'll see the three prices i'm talking about)
Is it possible to define which price checkbox is checked when clicking on the corresponding price on the frontpage?
So that if i'm clicking on 209,- price on the bottom of the frontpage - that it will check the corresponding checkbox on the "tilmeld" page when redirected.
thanks.
This is a fully functional code that will let you achieve what you require. I hope, this helps. :)
Here's a working demo:
https://plnkr.co/edit/3cHgLoBerPBH9Bj6RH7Y?p=preview
Main.html
Change your hyperlinks to the form of by appending ?money=value:
209
101
300
Next.html
Suppose your radio buttons are of the form:
<form action="">
<input type="radio" value="209" id="c209"> 209<br>
<input type="radio" value="101" id="c101"> 101<br>
<input type="radio" value="300" id="c300"> 300
</form>
Add this script to the end of your body tag:
<script>
var value;
var url1;
function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;
if (query === url || query === "") return;
for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=", 2);
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);
if (!parms.hasOwnProperty(n)) parms[n] = [];
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}
url1 = parseURLParams(window.location.href);
for(key in url1) {
if(url1.hasOwnProperty(key)) {
value = url1[key];
}
}
document.getElementById("c"+value).checked= true;
</script>
How this works?
In the main.html you are passing the values to the URL by appending
the values in the url itself as ?money=209 when 209 is the value
that will be validated and the appropriate radio button will be
selected.
In the next.html we have a URLparser which will extract the values
followed by ?money="value" and store it in the variable "Value".
According to this variable, we have a form with radio buttons of IDS
c209,c300,c101 and so on. We'll just use a simple expression:
document.getElementById("c"+value).checked= true;
This appends "c"with the value obtained. This makes it as c209 and the
appropriate radio button is selected.
Define a variable on window localStorage like:
window.localStorage.setItem('tmp', 'something');
This must work for you.

Allow Single Type Input in Html

Ok so i have a Chatroom, People are required to type in a name and once done they may chat. But alot of times people take other peoples name. So what i need is kind of like a limited input
here is the input:
<input type="text" class="input-block-level" ng-model="name" ng-change="setName()" placeholder="Your Name" maxlength="10" required></div>
I need this so if i type in the name Bob, no one can use that name again
Incase you want the website: https://project-js-imthatguy.c9users.io/
One possible way to check amongst a given set...
used a simple for loop for this example
Inside your send function that you have defined, perform a check:
$scope.send = function send() {
var isDuplicated = 0
for (i = 0; i < $scope.roster.length; i++){
if ($scope.roster[i] == $scope.name){ isDuplicated++ }
}
if (isDuplicated > 1){
//make an error message appear here
//quick and dirty solution
alert('Please choose a name that has not been taken by someone else')
//suggestion set a variable here to true and then use that variable to show/hide a div below the user input area
}
else {
console.log('Sending message:', $scope.text);
socket.emit('message', $scope.text);
$scope.text = '';
}
};

How to create an input field (HTML) that spans two lines

I want to be able to use an <input> field type of control but allow only two lines.
At the moment I am using two fields but was wondering if anyone can come up with a solution to allow input (similar to a textarea) but no more than two lines. I control the width etc of the field.
For reference, Jquery and Bootstrap 3 are loaded.
Any help much appreciated.
try this
var element = document.getElementById('tworows');
make2Lines(element);
function make2Lines(el){
el.setAttribute('rows', 2); // limit height to 2 rows
// el.setAttribute('wrap', 'off'); // ensure no softwrap is not required anymore if we limit the length
el.addEventListener('keydown', limit); // add listener everytime a key is pressed
function limit(e){
if(e.keyCode == 13 && this.value.indexOf('\n')>-1){
// 13 is the ENTER key and \n is the value it make in the textarea
// so if we already have a line break and it's the ENTER key, we prevent it
e.preventDefault();
}
// async to let the dom update before changin the value
setTimeout(limitRow.bind(this), 0);
}
function limitRow(){
var maxLength = 10;
var rows = this.value.split('\n');
rows.forEach(cutOverflow)
this.value = rows.join('\n');
function cutOverflow(row, index, rows) {
rows[index] = row.substring(0, maxLength);
// this if is only if you want to automatically jump to the next line
if (index === 0 && row.length > maxLength)
rows[1] = row.substring(maxLength) + (rows[1] || '');
}
}
}
<textarea id="tworows"></textarea>
short version : function make2Lines(a){function b(a){13==a.keyCode&&this.value.indexOf("\n")>-1&&a.preventDefault(),setTimeout(c.bind(this),0)}function c(){function c(b,c,d){d[c]=b.substring(0,a),0===c&&b.length>a&&(d[1]=b.substring(a)+(d[1]||""))}var a=10,b=this.value.split("\n");b.forEach(c),this.value=b.join("\n")}a.setAttribute("rows",2),a.addEventListener("keydown",b)}
Two ways come to mind:
You could use a <textarea> instead, and augment it with some script that only allows two lines.
You could continue to use two <input> fields, but style them so they stack on top of each other to create the illusion of one field. You might still need a bit of script to take care of some usability annoyances, such as pressing ENTER to go from line one to line two.
If you are talking about wrapping lines if the text is too long, according to documentation <input type="text"> cannot wrap text.
However, if you are talking about limiting the character length, you could use the maxlength attribute like- <input type="text" maxlength="10">
An input field can only display one line http://www.w3.org/TR/html-markup/input.text.html#input.text. For multiline you need to use textarea and set the rows attribute. If you need two separate values you can do it after in PHP, Javascript or other means.
<textarea class="form-control" rows="2">The default text or empty for nothing this is passed as value for this field</textarea>

HTML - Text Box - JS Function for Characters Left like SO

<input type='text' name='one' id='oneID' maxlength="150">
i need the JS to display the number of characters left that user can input
a picture is worth a 1000 words so no more explanation required...
Bind a function to the onkeyup event that counts the number of characters entered and displays how much is remaining.
Example:
var e = document.getElementById('oneID'),
f = document.getElementById('countDiv'); // some element where the count will be displayed
e.onkeyup = function() {
f.innerHTML = (e.maxLength - e.value.length) + ' characters remaining';
}