How to replace text when selected in javascript - javascript

I have the below phone number validation which automatically picks up brackets based on the condition.
I have an issue here, after giving the 10 digit phone number when we try to select the whole number and start typing on top of it, length of the value remains same (14) and brackets are not picking up and condition goes wrong.
Length should be cleared in this case.
Where am I missing?
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.validatePhoneNumber = function(e){
var key = e.charCode || e.keyCode || 0;
// var regex = /^[0-9.\-\(\)]*$/;
var text = $('#phoneNumber');
console.log(text.val());
if ((e.which < 48 || e.which > 57)) {
e.preventDefault();
} else if (key !== 8 && key !== 9) {
if ((text.val().length === 0) && (!e.ctrlKey)) {
text.val(text.val() + '(');
}
if (text.val().length === 4) {
text.val(text.val() + ') ');
}
if (text.val().length === 9) {
text.val(text.val() + '-');
}
}
return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" class="input-sm form-control" id="phoneNumber"
ng-model="search.phonenumber" placeholder="Phone Number"
ng-keypress="validatePhoneNumber($event)"
ng-paste="$event.preventDefault();"
ng-init="paste=false" maxlength="14">
</div>

I have used keyup here hope this will help you
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" class="input-sm form-control" id="phoneNumber" ng-model="search.phonenumber" placeholder="Phone Number" ng-keyup="validatePhoneNumber($event)" ng-paste="$event.preventDefault();" ng-init="paste=false" maxlength="14">
</div>
</body>
</html>
JS
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.validatePhoneNumber = function(e) {
var key = e.charCode || e.keyCode || 0;
// var regex = /^[0-9.\-\(\)]*$/;
var text = $('#phoneNumber');
console.log(text.val());
if ((e.which < 48 || e.which > 57)) {
e.preventDefault();
}
if(text.val().length === 1) {
if(!isNaN(text.val())) {
text.val('(' + text.val());
}
}
if ((text.val().length === 0) && (!e.ctrlKey)) {
text.val(text.val() + '(');
}
if (text.val().length === 4) {
text.val(text.val() + ') ');
}
if (text.val().length === 9) {
text.val(text.val() + '-');
}
return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
}
});

You may want to take a look at angular-input-masks package. It appears to implement the required logic by ui-us-phone-number-mask directive:
var app = angular.module('myApp', ['ui.utils.masks']);
app.controller('myCtrl', function() {});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-input-masks/4.2.1/angular-input-masks-standalone.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input ui-us-phone-number-mask type="text" class="input-sm form-control" id="phoneNumber" ng-model="search.phonenumber" phone-number placeholder="Phone Number" ng-paste="$event.preventDefault();" ng-init="paste=false" maxlength="14">
</div>

Related

javascript changing the value of a keyboard key

I have a textfield takes only letters, I want if I pressed (a) I get (b) and if I pressed (b) get (c)...etc, if I pressed (z) get alert("there is no letters after")
<input type="number" id="example" onkeypress="return numbersKey(event)">
<p id="demo"></p>
<input type="text" id="example2" onkeypress="return lettersOnly(event)">
<script>
var myinput = document.getElementById('example'),
myp = document.getElementById('demo');
function numbersKey(evt) {
// Only ASCII charactar in that range allowed
var ASCIICode = event.keyCode;
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
};
}
function lettersOnly()
{
// Only ASCII character in that range allowed
var charCode = event.keyCode;
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8){
return String.fromCharCode(event.keyCode + 1);
}
else
return false;
}
Paste this complete code and run it once to see.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="example2" onkeypress="lettersOnly(event)">
<p id="demo"></p>
</body>
<script>
function lettersOnly(event) {
var charCode = event.keyCode;
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8){
if(charCode == 90 || charCode == 122){
document.getElementById('demo').innerHTML = "There's no letter after";
}
else{
document.getElementById('demo').innerHTML = String.fromCharCode(event.keyCode + 1);
}
}
else{
document.getElementById('demo').innerHTML = "Not Letter";
}
}
</script>
</html>

Format an input field for US number

I am having a small issue with my code and I am not able to crack it, the format I want is
+1 (888) 123-4567 . However I have achieved this (544)-646-4646 format. But I am unable to figure how can i get +1 already written and when someone types number the remaining should be formatted as the above example.
so in simple words I need +1 to be already typed and rest when typed by user would give the same format as the code.
Here is the code
$(document).ready(function(){
/***phone number format***/
$(".phone-format").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3 && curval.indexOf("(") <= -1) {
$(this).val("(" + curval + ")" + "-");
} else if (curchr == 4 && curval.indexOf("(") > -1) {
$(this).val(curval + ")-");
} else if (curchr == 5 && curval.indexOf(")") > -1) {
$(this).val(curval + "-");
} else if (curchr == 9) {
$(this).val(curval + "-");
$(this).attr('maxlength', '16');
}
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input class="phone-format" value="" type="text" placeholder="Phone Number">
</body>
</html>
You can try this:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input class="phone-format" value="+1 " type="text" placeholder="Phone Number">
</body>
</html>
And in js file:
$(document).ready(function(){
/***phone number format***/
$(".phone-format").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 6 && curval.indexOf("(") <= -1) {
$(this).val(curval.substring(0, 2) + " (" + curval.substring(3) + ")" + "-");
} else if (curchr == 7 && curval.indexOf("(") > -1) {
$(this).val(curval + ")-");
} else if (curchr == 8 && curval.indexOf(")") > -1) {
$(this).val(curval + "-");
} else if (curchr == 12){
$(this).val(curval + "-");
$(this).attr('maxlength', '16');
}
});
});
Try the jquery input mask plugin
You just need to specify the mask/format you want your input to be in and it does the job.
$(window).load(function()
{
$('#phone').inputmask({"mask": "+1(999) 999-9999"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.1.62/jquery.inputmask.bundle.js"></script>
<input type='text' id='phone' />

Hide <p> element if innerHTML is "0" or empty

I am trying to make a simple calculator but I am stuck; I need to hide some elements. My code is shown with comments below.
function ekogroszek() {
var p = document.getElementById("powierzchnia").value;
var w = document.getElementById("wysokosc").value;
var k = p * w;
var e = 7.8;
var s = k * e;
document.getElementById("wynik").innerHTML = s;
}
$('#wysokosc').keypress(function(event) {
if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
$(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}).on('paste', function(event) {
event.preventDefault();
});
$('#powierzchnia').keypress(function(event) {
if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
$(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}).on('paste', function(event) {
event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span>First field</span>
<input class="polekalkulacji" type="text" id="powierzchnia" name="powierzchnia" placeholder="np. 120">
</div>
<div>
<span>Second</span>
<input class="polekalkulacji" type="text" id="wysokosc" name="wysokosc" placeholder="np. 2.8">
</div>
<button onclick="ekogroszek()">Calculate</button>
<!--- Show below elements only if number (p id=wynik) is bigger than: "0" and field is filled --->
<p id="zapotrzebowanie">Result is:</p>
<p type="text" id="wynik"></p>
So as you can see I need to show these two "p" elements only if id=wynik is filled and bigger than 0. How would I go about doing this?
If your goal is to keep them hidden until anything is written on them, and also the value on it is greater than 0, then the best way to achieve it is by hidding them on default with:
<p id="zapotrzebowanie" style="display: none;">Result is:</p>
<p type="text" id="wynik" style="display:none;"></p>
And when you are writting HTML to them, show them with jQuery:
function ekogroszek() {
var p = $("#powierzchnia").val();
var w = $("#wysokosc").val();
var k = p * w;
var e = 7.8;
var s = k * e;
document.getElementById("wynik").innerHTML = Math.trunc(s);
if(s>0){
$("#zapotrzebowanie").show();
$("#wynik").show();
}
}
You can check a working version of your code in this fiddle:
https://jsfiddle.net/0arcxze4/2/
Why not simply check to the value:
if($(this).val() == '0' || $(this).val() == '' ) {
$('#wynik').hide();
}
You may show with jquery and at initial phase hide the html element with css. But I see you're showing them after calculating? Then, that's just fine.
But if you want the harder way then it is:
$('#wynik').css('display', function(i, v) {
return ($(this).text() == '0' || $(this).text() == '') ? 'none' : 'block'
});

Blocking spaces ASP MVC and Javascript

I'm trying to validate the code that users enter in my view. I want it to be MAJ and only letters and numbers. So no ""/(!/ or spaces. Everything works just fine except for the spaces...
Here's the code
#Html.TextBoxFor(m => m.Code, new { #onkeydown = "onKeyDown(this);", #class = "input-visual-helper form-control", placeholder = #MyProject.Resources.home.ActivationCode })
<script type="text/javascript">
function onKeyDown(a) {
var charCode = (a.which) ? a.which : event.keyCode
setTimeout(function () {
a.value = a.value.toUpperCase();
}, 1);
return ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || (charCode >= 48 && charCode <= 57));
}
</script>
I did a console.log of the condition in the return and it logs false when I type the space (code 32). I even tried doing if(charCode ==32) return false. Still not working... The interface keeps doing a space in the textbox.
Any help would be greatly appreciated.
Thanks
$("#jam").keydown(function (e) {
if (e.keyCode == 32) {
return false;
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<input id="jam"/>
</body>
</html>
Something like this?
<script type="text/javascript">
$("#targetElement").keydown(function (e) {
if (e.keyCode == 32) {
return false;
}
});
</script>
https://jsbin.com/didohiloni/1/edit
For the MVC textbox you would append new { id = "youid" } in there
If anyone wants a complete version of the code
the control :
#Html.TextBoxFor(m => m.Model.Code, new { #onkeydown= "onKeyDown(this)", #id = "bindingCode", #class = "input-visual-helper form-control", placeholder = #Resources.home.Code })
<script type="text/javascript">
//No spaces and no special characters
$(document).on('keypress', '#bindingCode', function (event) {
if (event.keyCode == 32) {
return false;
}
var regex = new RegExp("^[A-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
key = key.toUpperCase();
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
// All Letters in maj
function onKeyDown(a) {
var charCode = a.which;
setTimeout(function () {
a.value = a.value.toUpperCase();
}, 1);
}
</script>

allowing only alphabets in text box using java script

I want to allow only alphabets in textbox using JavaScript
I used the code:
var nam=f.nm.value;
if(!isNaN(nam))
region.innerHTML="alphabets only";
It is not working and allows numbers as well. How can i fix this?
<html>
<head>
<title>allwon only alphabets in textbox using JavaScript</title>
<script language="Javascript" type="text/javascript">
function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
</script>
</head>
<body>
<table align="center">
<tr>
<td>
<input type="text" onkeypress="return onlyAlphabets(event,this);" />
</td>
</tr>
</table>
</body>
</html>
just use onkeypress event like below:
<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
From kosare comments, i have create an demo http://jsbin.com/aTUMeMAV/2/
HTML
<form name="f" onsubmit="return onlyAlphabets()">
<input type="text" name="nm">
<div id="notification"></div>
<input type="submit">
</form>
javascript
function onlyAlphabets() {
var regex = /^[a-zA-Z]*$/;
if (regex.test(document.f.nm.value)) {
//document.getElementById("notification").innerHTML = "Watching.. Everything is Alphabet now";
return true;
} else {
document.getElementById("notification").innerHTML = "Alphabets Only";
return false;
}
}
You can use HTML5 pattern attribute to do this:
<form>
<input type='text' pattern='[A-Za-z\\s]*'/>
</form>
If the user enters an input that conflicts with the pattern, it will show an error dialogue automatically.
You can try:
function onlyAlphabets(e, t) {
return (e.charCode > 64 && e.charCode < 91) || (e.charCode > 96 && e.charCode < 123) || e.charCode == 32;
}
:::::HTML:::::
<input type="text" onkeypress="return lettersValidate(event)" />
Only letters no spaces
::::JS::::::::
// ===================== Allow - Only Letters ===============================================================
function lettersValidate(key) {
var keycode = (key.which) ? key.which : key.keyCode;
if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))
{
return true;
}
else
{
return false;
}
}

Categories

Resources