How to auto add a hyphen in user input using Javascript? - javascript

I am trying to validate and adjust user input for a zip code to match the format: xxxxx OR xxxxx-xxxx
Is there a simple way using javascript to add the hyphen (-) automatically if the user enters more than 5 digits?

Pretty sure there is! Just gotta check how many characters the inputted string has, and if it's 5, add a hyphen to the string :)
var input = document.getElementById("ELEMENT-ID");
input.addEventListener("input", function() {
if(input.value.length === 5) {
input.value += "-";
}
}

Try the following.
function add_hyphen() {
var input = document.getElementById("myinput");
var str = input.value;
str = str.replace("-","");
if (str.length > 5) {
str = str.substring(0,5) + "-" + str.substring(5);
}
input.value = str
}
<input type="text" id="myinput" value="a" OnInput="add_hyphen()"></input>

Anna,
The best way to do it would be to use a regular expression. The one you'll need is:
^[0-9]{5}(?:-[0-9]{4})?$
You would ten use something like:
function IsValidZipCode(zip) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zip);
if (isValid)
alert('Valid ZipCode');
else {
alert('Invalid ZipCode');
}
}
In your HTML call it like this:
<input id="txtZip" name="zip" type="text" /><br />
<input id="Button1" type="submit" value="Validate"
onclick="IsValidZipCode(this.form.zip.value)" />
For more on Regular Expressions this is a good article:
Regular Expressions on Mozilla Developers Network

You can try using simple javascript function as follows
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script>
function FN_HYPEN(){
var input = document.getElementById("USER");
if(input.value.length === 5) {
input.value += "-";
}
}
</script>
</head>
<body>
<INPUT ID="USER" TYPE="TEXT" onKeypress="FN_HYPEN();"/>
</body>
</html>

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>

Remove all letters from input value

I want to make a button that clears an input type='text' from all its letters. I want it to, when clicked, remove all characters except numbers and commas.
<input type="text" id="txt" value="1a,2b,3c">
<input type="button" id="reml" value="Remove Letters" onclick="???????">
I was thinking it would be something like:
onclick="document.getElementById('reml').value.replace(a[],'');
a = ['a','b','c',etc.];
But I'm not sure if something like that'd work...
Any ideas?
Something along these lines.
function clearInvalid() {
var input = document.getElementById('txt')
input.value = input.value.replace(/[^\d,]/g,'')
}
<input type="text" id="txt" value="1a,2b,3c">
<input type="button" id="reml" value="Remove Letters" onclick="clearInvalid()">
Make this the onclick code:
var theinput = document.getElementById('reml')
theinput.value = theinput.value.replace(/[^\d,]/g,'')
This uses a regex to find all non-digit and comma characters and replaces them with an empty string
You could use a function like the following one to transform the text:
function transform(s) {
var out = "";
for (var index = 0; index < s.length; ++index) {
if ((!isNaN(s[index])) || (s[index] === ',')) {
out += s[index];
}
}
return out;
};
You can use regex to do this, and jQuery can make your code even shorter:
<html>
<input type="text" id="txt" value="1a,2b,3c">
<input type="button" id="reml" value="Remove Letters">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("#reml").on("click", function(event) {
$("#txt").val($("#txt").val().replace(/[^\d,]/g, ''));
});
</script>
</html>

How to make a word a link if the user has input # before it?

I am using this code:
<form oninput="x.value=a.value">Account Info <br>
<input type="text" id="a">First Name<br>
UserName <output name="x" for="a"></output>
</form>
I want i such a way that if the user inputs a word and he has place # before the word without space then how to make the word as a link. Means the tag which happens in facebook. Can it be done with java script and how.
This was just the example to demonstrate i want to intergrate this type in my project as comments. And it will be with php.
Thanks
Here's one example to check. It works with enter keypress and even prevents for adding same tags over again: http://codepen.io/zvona/pen/KpaaMN
<input class='input' type="text" />
<output class='output'></output>
and:
'use strict';
var input = document.querySelector('.input');
var output = document.querySelector('.output');
input.addEventListener('keyup', function(evt) {
if (evt.keyCode !== 13 || !input.value.length || ~output.textContent.indexOf(input.value)) {
return;
}
var tag = document.createElement('a');
tag.appendChild(document.createTextNode(input.value));
if (input.value.startsWith("#")) {
tag.setAttribute("href", input.value);
}
output.appendChild(tag);
input.value = "";
}, false);
<form>Account Info <br>
<input type="text" id="a">First Name<br/>
<output id="result" name="x" for="a"></output>
<button type="button" onclick="changeVal(document.getElementById('a').value)">Click</button>
</form>
<script>
function changeVal(value1){
var dt = value1.split(" ");
document.getElementById("result").innerHTML = "";
for(var t=0; t < dt.length; t++){
if(dt[t].startsWith("#")){
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" <a href='#'>"+dt[t]+"</a>";
}
else{
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" "+dt[t];
}
}
}
</script>
Checkout Jsfiddle demo
https://jsfiddle.net/tum32675/1/
You could use a textarea to input and a render to show the output. Then hiding the input and showing the output only. But that's another
story.
If you use a contentEditable div, you can actually insert and render the html from it in the same component. Check it out!
$(document).on("keyup","#render", function(){
var words = $(this).text().split(" ");
console.log(words);
if (words){
var newText = words.map(function(word){
if (word.indexOf("#") == 0) {
//Starts with #
//Make a link
return $("<div/>").append($("<a/>").attr("href", "#").text(word)).html();
}
return word;
});
}
$(this).empty().append(newText.join(" "));
placeCaretAtEnd( $(this)[0]);
});
Here is the Plunker
Thanks for the attention.

check text box value is according to a prefix

I have text box.
Users can enter Student Id into that.
Student id is in this format DIP0001.
First three letters should be DIP and the remaining 4 digits should be numeric and can only upto 4 characters.
So how can I check whether entered data is in this format using javascript.
Please help.....
You could build a regular expression pattern and test it against that value to see if it matches that exact pattern.
HTML FILE:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
</head>
<body>
<label for="studentId">Student ID</label>
<input id="studentId" type="text">
<button id="btn" type="button">Validate</button>
// Embedded script so that you don't have to load an external file
<script>
var input = document.getElementById('studentId');
var btn = document.getElementById('btn');
var pattern = /DIP+\d{1,3}/g;
btn.addEventListener('click', function(){
if(pattern.test(input.value)) {
alert('It enter code here`atches!');
}else {
alert('It does not match!');
}
});
</script>
</body>
</html>
JS FILE:
// This pattern looks something like this: DIP0000
var pattern = /DIP+\d{1,3}/g;
// studentId is the ID of the input field that contains the Student ID
var studentIdInput = document.getElementById('studentId');
// Check the pattern against the provided Student ID
if(pattern.test(studentIdInput.value)) {
alert('It matches the pattern!');
}
EDIT 1: I have built the functionality in the following JSFiddle: http://jsfiddle.net/vldzamfirescu/QBNrW/
Hope it helps!
EDIT2: I have updated the JSFiddle to match any other combinations up to 4 digits; check it out: http://jsfiddle.net/vldzamfirescu/QBNrW/1/ Let me know if it solved your problem!
try this code
<html>
<head>
<script>
function validate(val) {
if (val.value != "") {
var filter = /^[DIP]|[dip]+[\d]{1,4}$/
if (filter.test(val.value)) { return (true); }
else { alert("Please enter currect Student Id"); }
val.focus();
return false;
}
}
</script>
</head>
<body>
<input id="Text1" type="text" onblur="return validate(this);" />
</body>
</html>
Use Regular Expresions.
If found a valid Student ID, the pattern will return true:
function validateStudentId(id) {
var re = /DIP[0-9]{4}/;
return re.test(id);
}
// Edited for use with a click event:
document.getElementById('button').addEventListener('click', function(){
if( validateStudentId(document.getElementById('textBox').value) ){
alert('correct');
}else{
alert('invalid ID');
}
});

JavaScript Replace Method for multiple textboxes

Can anyone please tell me how I can use the replace method to replace a character if it occures in more than one textbox without having to write separate function for each textbox.
The code below is the basic way to use the replace method but it only allows for one textbox.
I'm sure I need a loop in there but I'm not sure how to use that without affecting the replace method.
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript">
function stringReplace(form) {
var replaceStr = form.textfield1.value
var pattern = /\'/g;
form.textfield1.value = replaceStr.replace(pattern, "''");
}
</script>
</head>
<body>
<form name="form1" method="post" action="JStest_redirect.asp">
<p>fname:
<input type="text" name="textfield1" size="20">
</p>
<p>lname:
<input type="text" name="textfield2" size="20">
</p>
<p>
<input onclick="return stringReplace(form)" type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>
You can do this:
function stringReplace(form) {
var $inputs = $(form).find('input:text');
var pattern = /\'/g;
$inputs.each(function () {
this.value = this.value.replace(pattern, "''");
});
return false; // Prevent the form from being submitted
}
This would find all the input type text within the form and replace their values.
If you wish to do it without jquery, you can use the getElementsByTagName() method.
function stringReplace(form) {
var pattern = /\'/g;
var inputs = form.getElementsByTagName("input");
var input;
for (var i = 0; i < inputs.length; i++) {
input = inputs[i];
if (input.type = 'text') {
var replaceStr = input.value;
input.value = replaceStr.replace(pattern, "''");
}
}
return false;
}
You seem to want
function stringReplace(form) {
$('input[type=text]').val(function(_, v) {
return v.replace(/\'/g, "''");
});
return false;
}
I added a return false at the end to prevent the form to be submitted on click. You probably want to have a separate button in your case.
I believe that fisrt you have to take all the values
function GetValue(){
var Contain = "";
$("#form1 :text").each(function(){
//add replace code here
});
}
You can add onchange function to all of you text input
function stringReplace(textField) {
var replaceStr = this.value
var pattern = /\'/g;
this.value = replaceStr.replace(pattern, "''");
}
and than you add
<input type="text" name="textfield1" size="20" onchange="stringReplace(this);">

Categories

Resources