In the below code the text box is restricting zero at starting position. But I want to allow only one zero at first position but not more than one. here is the example
Eg:- 0.1012400==> correct
000.4545000==>not correct
0154==> correct
00154 ==> not correct
$('input#abc').keypress(function(e){
if (this.selectionStart == 0 && (e.which == 48 || e.which == 46 )){
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
You can simply test if there is 2 consecutive zero at the start and if yes you remove one:
$('input#abc').on('keypress keydown keyup',function(e){
var v = $(this).val();
if(v.length >=2 && v[0]=='0' && v[1]=='0') {
$(this).val(v.substring(1));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
UPDATE
Here is a code if you want to consider the minus sign at the start:
$('input#abc').on('keypress keydown keyup', function(e) {
var v = $(this).val();
if (v.length >= 2 && v[0] == '0' && v[1] == '0') {
$(this).val(v.substring(1));
} else if (v.length >= 3 && v[0] == '-' && v[1] == '0' && v[2] == '0') {
$(this).val('-' + v.substring(2));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
You could check the final string like
$('input#abc').on('change', function () {
console.log(this.value.indexOf('00') === 0);
});
Related
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' />
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'
});
Hi i am trying to restrict user to input 2 digit number after the decimal.The below functionality is working but i am not able to modify the last two digit.suppose I have entered number 3456.78 and i want to modify 3456.68 it is not allowing.
$('.PMT_AMT').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Here's one possibility that uses a regular expression. Save the old input value on keypress, and if the new value on keyup does not validate, reset to that old value.
You need to validate on keypress as well, because otherwise, if the user types very fast, an invalid value can be saved:
const re = /^\d+(\.\d{0,2})?$/;
let oldVal;
$('.PMT_AMT').keypress(function(event) {
const { value } = this;
if (re.test(value)) oldVal = value;
});
$('.PMT_AMT').keyup(function(event) {
const newVal = this.value;
if (!re.test(newVal)) this.value = oldVal;
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
This solution creates a prediction and tests the regular expression against that instead.
$('.PMT_AMT').keypress(function(event) {
if(!/^\d*(\.\d{0,2})?$/.test(
this.value.slice(0, this.selectionStart)
+ String.fromCharCode(event.which)
+ this.value.slice(this.selectionEnd)
)) event.preventDefault();
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Why use jQuery and not just browser functionality?
<input type="number" step="0.01">
On submit the browser will check if the submitted value of the input field has maximum two decimals.
I have a button and an input area. When the input's length is filled (14) - then the button's class will be active. That currently works, however, when the user pastes a value into the input area, the length is zero until the user enters something else. My goal is to display the active class on the button when the paste is done if the length of the value is 14.
JS
$('#number', '#form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
document.getElementById('number').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
HTML
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'>
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>
You should use the input event. This event is triggered when eve the input changes. keyup and keydown will fire even if the input hasn't changed. Pressing CTRL will trigger keydown even if nothing has changed. input will only be triggered if it has changed, ie: CTRL + V (paste)
$('#number', '#form')
.on('input', function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'>
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>
Also use another event input so it triggers your function on keydown and on input as well. Check out this working example using your code
$('#number', '#form').on('keydown input',function(){});
$('#number', '#form')
.on('keydown input', function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'><br /><br />
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>
<div>
<input type="text" class="allownumericwithdecimal"/>saadad
</div>
$(".allownumericwithdecimal").live("keypress keyup ", function (event) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
var text = $(this).val();
if (!((event.which >= 48 && event.which <= 57) || event.which == 8 || event.which == 46 || event.which == 110 || event.which == 0)) {
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.'), text.indexOf('.').length).length > 2)) {
//event.preventDefault();
}
}
var text = $(this).val();
if ((event.which >= 48 && event.which <= 57) && (text.indexOf('.') != -1)) {
if ((text.substring(text.indexOf('.'), text.indexOf('.').length).length) > 2) {
//event.preventDefault();
}
if (event.which == 190) {
//event.preventDefault();
}
}
if (text.indexOf('.') != -1 && event.which == 190) {
if (text.match("^[0-9]+(\.[0-9]{0,2})?$")) {} else {
$(this).val('');
}
}
if (text.indexOf('.') == -1 && text.length > 7 && (event.which != 190 && event.which != 8 && event.which != 46 && event.which != 110 && event.which != 0)) {
event.preventDefault();
}
});
http://jsfiddle.net/Lx9h2smh/
The problem is If I type a value in textBox say 3434 and now I want to make it 35434 by putting cursor after 3 and pressing 5, it works fine in Firefox and IE but in chrome the 5 get added after value and it becomes 34345.
The culprit line is one which replace non numeric characters.
How to handle this issue??
Try this code, it runs. jsFiddle
I just do a test
if ( /[^0-9\.]/g.test($(this).val()) ) {
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
}
Explain
You just make sure that the user enter the value of what you want. You replace if the entered value is not an integer. Your regex mean: "Those which are not integer or dot (.), replace them with an empty value". That why You need to make this test. Therefore, if the user enters the value you want, it doesn't do the action replace and it doesn't pass to the test.
$(".allownumericwithdecimal").live("keypress keyup ",function (event) {
var caretP= $(this).getCursorPosition();
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
var text = $(this).val();
if (!((event.which >= 48 && event.which <= 57) || event.which ==8 || event.which ==46 || event.which ==110 || event.which ==0) )
{
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.'), text.indexOf('.').length).length > 2)) {
//event.preventDefault();
}
}
var text = $(this).val();
if((event.which >= 48 && event.which <= 57) && (text.indexOf('.') != -1))
{
if((text.substring(text.indexOf('.'), text.indexOf('.').length).length)>2)
{
//event.preventDefault();
}
if(event.which==190)
{
//event.preventDefault();
}
}
if(text.indexOf('.') != -1 && event.which==190 )
{
if(text.match("^[0-9]+(\.[0-9]{0,2})?$")){
}
else{
$(this).val('') ;
}
}
if(text.indexOf('.') == -1 && text.length>7 && (event.which!=190 && event.which !=8 && event.which !=46 && event.which !=110 && event.which !=0)){
event.preventDefault();
}
$(this).selectRange(caretP,caretP);
});
(function($) {
$.fn.selectRange = function(start, end) {
return this.each(function() {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if (document.selection) {
// IE
input.focus();
}
return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
}
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div>
<input type="text" class="allownumericwithdecimal"/>saadad
</div>
kepress seems to be the culprit when I changed the fiddle to just use keyup the replacement happened correctly (though the cursor shifted to the end)
http://jsfiddle.net/Lx9h2smh/1/
Just remove the 'keypress' event keypress event is very similar to the keydown event. If you press a button keypress event cannot identify the character. In your code it takes as current input Empty so it replace the character.