textbox value with hard coded dash - javascript

I have a textbox in the page. <input type="text" id="cell">
I have used below jquery....
i = 0;
$(document).ready(function () {
$("#cell").keypress(function () {
i += 1;
if (i == 4) {
var cellValue = $("#cell").val() + "-";
$("#cell").val(cellValue);
}
});
});
whenever an user types 12345678 (or any number) it automatically shows 123-45678. But problem is when user uses backspace or delete and then starts typing 12345678 it does not show 123-45678. Please help

i should be the length of the value , not the number of times you pressed the key
Try this -
$("#cell").keypress(function () {
i = $(this).val().length;
if (i == 3) {
var cellValue = $("#cell").val() + "-";
$("#cell").val(cellValue);
}
});
Demo --> http://jsfiddle.net/KZmc9/2/

Try
$(document).ready(function(){
$("#cell").keypress(function(){
if (this.value.length == 3) {
$("#cell").val(this.value + "-");
}
});
});
Demo: Fiddle

I would split the input into two, because otherwise users have to delete the dash if they want to delete the 3rd number.
http://jsfiddle.net/TATnK/
$(document).ready(function() {
$('#cell_1').on('input', function(e) {
if($(this).val().length == 3) {
$('#cell_2').focus();
}
});
$('#cell_2').keyup(function(e) {
if(e.which == 8 && $(this).val().length == 0) {
$('#cell_1').focus();
}
});
});

Related

How to add forward slash automatically in keyup function

I'm having some field in which when the user types after 2nd alphabet, I need to add forward slash automatically.
Is this possible in jquery?
<input type="text" class="someclass"/>
$(document).on('keyup','.classname', function(){
var count = $(this).val();
if(count == 2)
{
// Need stuff here
}
});
You can use:
$(document).on('keyup','.someclass', function(){
var count = $(this).val().length;
if(count == 2 && e.keyCode != 8){
$(this).focus().val(function( index, value ) { return value + "/ " ; });
}
});
You could do this:
$(document).on('keyup', '.someclass', function(e) {
var count = $(this).val().length;
if (count == 2) {
$(this).val($(this).val() + "/");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="someclass" />

jQuery: Compact way to fetch values of all input fields?

I have a form with five input fields and a register button ('.register').
I want to enable the register button ONLY IF all fields have at least one character.
Here comes my code:
$(document).ready(function() {
// when page loads
$('.register').addClass('a_unclickable');
// Input validation
// Are all fields filled out?
$('input').on('keyup', function() {
var un_value = $('#username_operators').val();
var fn_value = $('#first_name_operators').val();
var ln_value = $('#last_name_operators').val();
var e_value = $('#email_operators').val();
var pw_value = $('#password_operators').val();
var pw_r_value = $('#password_repeat_operators').val();
if ((un_value.length > 0) && (fn_value.length > 0) && (ln_value.length > 0) && (e_value.length > 0) && (e_value.indexOf('#') !== -1) && (pw_value.length > 0) && (pw_r_value.length > 0)) {
$('.register').removeClass('a_unclickable');
} else {
$('.register').addClass('a_unclickable');
}
})
});
I have the feeling that there is a much easier way to achieve the same result. Does anyone of you have a compact suggestion?
That's quiet compact:
$(document).ready(function() {
// when page loads
$('.register').addClass('a_unclickable');
// Input validation
// Are all fields filled out?
$('input').on('keyup', function() {
$('.register').removeClass('a_unclickable');
$('input').each(function() {
if ($(this).val() === '') {
$('.register').addClass('a_unclickable');
}
});
})
});
A couple of things come to mind. First:
$('input').on('keyup', function() {
var valid = true;
$('#username_operators, #first_name_operators, #last_name_operators, #email_operators, #password_operators, #password_repeat_operators').each(function() {
if (/^\s*$/.test(this.value)) {
valid = false;
}
});
if (valid) {
$('.register').removeClass('a_unclickable');
}
else {
$('.register').addClass('a_unclickable');
}
});
You can combine all the Ids into one CSS selector. Really the cleanest way is to add a class name to each required input, then utilize event.target.form to find all required fields inside the form.
$('input').on('keyup', function(event) {
var valid = true;
$(event.target.form).find(".required").each(function() {
if (/^\s*$/.test(this.value)) {
valid = false;
}
});
if (valid) {
$('.register').removeClass('a_unclickable');
}
else {
$('.register').addClass('a_unclickable');
}
});
Wrap the inputs in a <div class="verifyLength" ></div>
Add the a_unclickable class to the register field by default.
Then jquery:
$('input').on('keyup', function() {
var emptyField = false;
$(".verfyLength").find("input").each(function()
{
if((this).val().length() <=0)
emptyField = true;
});
if(emptyField)
$('.register').addClass('a_unclickable');
else
$('.register').removeClass('a_unclickable');
});
Here you go JSFiddle
var arr = [un_value, fn_value, ln_value, e_value, pw_value, pw_r_value];
$.each(arr,function(i,item){ if(item.length > 0){
$('.register').removeClass('a_unclickable');
} else {
$('.register').addClass('a_unclickable');
}})
if you are able to read all the values with selector you could pass them
like:
$.each($('input'),function(i,item){ if($(item).val().length > 0){
$('.register').removeClass('a_unclickable');
} else {
$('.register').addClass('a_unclickable');
}})
Have a look at this jsfiddle:
var i = 0, count = 0;
$.each($( ":input" ), function( index, value ) {
if(value.value.length > 0) {
count++;
}
});
if(count === 6) {
console.log(true);
} else {
console.log(false)
}

How to restrict paste function after the maxlength

I have got a task to restrict paste function when it comes to maximum. For that I used the code
$(document).on('keyup', '.txtStyle', function (e) {
debugger;
var charsSoFar = $('#' + container_id).val().length;
remaining = 500 - charsSoFar;
$('#rem_' + container_id).text('Characters remaining ' + remaining);
if (charsSoFar > 500) {
alert("Hai");
}
});
How can I restrict the Paste function? Please help
As my understanding you want to stop user input once its reach max, so i suggest
if (textbox.val().length >500 )
textbox.val(textbox.val().substring(0,500));
It will give illusion that after 500 char user can't input or paste in textbox.
Take look on this..... This will help you.
if (event.ctrlKey==true && (event.which == '118' || event.which == '86')) {
alert('Paste Restricted!');
e.preventDefault();
}
Demo : http://jsfiddle.net/6Gdkk/
$(document).on('keyup', '.txtStyle', function(e) { debugger;
var charsSoFar = $('#' + container_id).val().length;
remaining = 500 - charsSoFar;
$('#rem_' + container_id).text('Characters remaining ' + remaining);
if (charsSoFar > 500) {
if (e.keyCode == 86 && e.ctrlKey) {
alert("Hai");
}
}
});

Jquery keydown() with number format not work correctly on android webview

I have encountered a strange behavior on android browser / webview. I was testing an input that will automatically format to phone number format "(xxx) xxx-xxxx". But then what happened was when I tapped or press any number on androids keyboard, the first input was like this "(x" but then the cursor was in between "(" and "x". Is there a way to put the cursor after "x" value?
I tested this on iPhone and windows web browsers and it works fine. Please let me know if there are mistakes on my jquery or javascripts.
Thanks
HTML CODE:
<html>
<head>
<title>Sample Phone Number Format</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<input type="text" id="phone" />
<script type="text/javascript">
$('#phone').on('keydown', function (event) {
objval = $(this).val();
if (event.keyCode == 46 || event.keyCode == 8) {} else {
if (!((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 95 && event.keyCode < 106) || (objval.length > 13))) {
event.preventDefault();
} else {
if (objval.length == 0) {
$(this).val(objval + '(');
alert(objval + '(');
} else if (objval.length == 4) {
$(this).val(objval + ') ');
alert(objval + ') ');
} else if (objval.length == 9) {
$(this).val(objval + '-');
alert(objval + '-');
} else if (objval.length >= 14) {
if (event.keyCode == 9) {
return;
} else {
event.preventDefault();
}
}
}
}
});
$('#phone').on('keydown', function (event) {
var objVal = $(this).val();
if(objVal.length < 14)
{
validateCallerForm(objVal + String.fromCharCode((96 <= event.keyCode && event.keyCode <= 105)? event.keyCode-48 : event.keyCode));
}
});
//Validates proper phone format, true if valid phone number, false otherwise
function isValidPhoneNumber(elementValue) {
var numberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
return numberPattern.test(elementValue);
}
//validates entire caller form, also updates css classes for proper response
function validateCallerForm(PhoneNumber) {
if (isValidPhoneNumber(PhoneNumber)) {
alert("true");
} else {
alert("false");
}
}
</script>
</body>
</html>
Giving +50 Bounty to who'm will answer this correctly
you have to first define listener for typing and copy-paste like below (not required) :
$("#phone").keyup( function() {
maskLine(this);
});
$("#phone").change( function() {
maskLine(this);
});
Then, to manage cursor placement, you have to cache previous phone number and then, you could compare difference and update cursor position if needed.
So declare, you have to declare a global array like this :
var _cacheElementValues = new Array();
At last, you can check the function below, it applies your mask to phone number field and manage cursor placement :
function maskLine( element ) {
element = $(element);
var maskedLine = '';
var line = element.attr('value');
// check the cache of the input and abord if no change since last treatment
if (_cacheElementValues[element.attr('id')] != undefined && _cacheElementValues[element.attr('id')] == line) {
return;
}
line = line.replace(/\D/g, ''); // remove all characters != digits
line = line.substring(0, 10);
if (line != '') {
// apply mask
if (line.length <= 2 ) {
maskedLine = "(" + line;
} else if (line.length < 6) {
maskedLine = line.replace(/^([0-9]{3})([0-9]{0,3})/g, '($1) $2');
} else {
// mask : '(XXX) XXX-XXXX'
maskedLine = line.replace(/^([0-9]{3})([0-9]{3})([0-9]{0,4})/g, '($1) $2-$3');
}
}
// define cursor position at the end of the input by default
var pos = maskedLine.length;
// Change cursor placement if necessary
if (typeof element[0].selectionStart != 'undefined') {
var start = element[0].selectionStart;
var end = element[0].selectionEnd;
var insText = element[0].value.substring(start, end);
// get current cursor placement
if (insText.length == 0) {
pos = start;
} else {
pos = start + insText.length;
}
// find how many digits typing since last mask application
var previousLength = 0;
if (_cacheElementValues[element.attr('id')] != undefined) {
previousLength = _cacheElementValues[element.attr('id')].replace(/\s/g, '').length;
}
var diff = maskedLine.replace(/\s/g, '').length - previousLength;
// if sum of new typing digit is > 0 : we change cursor placement
if (diff > 0) {
pos += (diff - 1) + Math.round((diff-1)/3);
if (pos%6 == 0 && maskedLine.length >= pos+1) pos++;
}
}
// update input data & cache
element.val(maskedLine);
_cacheElementValues[element.attr('id')] = maskedLine;
// update cursor placement
element[0].selectionStart = element[0].selectionEnd = pos;
}
You can find this example on jsFiddle : http://jsfiddle.net/UE9LB/5/
I hope this little explantion can solve your problem ;)
Enjoy !
ps: i apologize for my poor english :s
I'd recommend at least starting with an existing plugin rather than going through your own isolated rounds of solving issues.
http://digitalbush.com/projects/masked-input-plugin/
https://github.com/igorescobar/jQuery-Mask-Plugin
The short answer is to set the selectionStart and selectionEnd properties of the input element. After you format the value, set these properties to this.value.length.
this.selectionStart = this.value.length;
this.selectionEnd = this.value.length;
But, where you are going to run into trouble is when the cursor is not at the end of the text. Eg, the user has manually positioned the cursor to a position within the text. To prevent the cursor from jumping to the end, you will need to detect the cursor position before you format the input, then put the cursor back in the appropriate position after formatting.
Edit: This jsFiddle may get you started, but isn't perfect yet.
I rewrite the code on my #phone keydown event and this will work on iPhone, Android, webkit browsers.
$('#phone').on('keydown', function (event) {
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39) {
// ignore if BKSPCE, left arrow, or right arrow
} else {
// validate if anything else
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0,3);
var next3 = string.substring(3,6);
var next4 = string.substring(6,10);
var string = ("(" + first3 + ") " + next3 + "-" + next4);
$(this).val(string);
}
});

How to stop writing in textbox by using JavaScript

I want to enter only 3 words in a textbox. My JavaScript code is below:
jQuery('#Txt_Report').keyup(function (event) {
if (event.which == 32) {
count = jQuery('#Txt_Report').val().split(' ').length;
if (count > 2) {
/////////////
//How can I stop entering text in txt_report anymore?
/////////////
});
}
}
As you see, I want to block user to not to enter more than 3 words. If someone knows how to handle this please help.
You can't preventDefault using keyup. Using keydown or keypress should work. Here is the example:
$('#Txt_Report').keypress(function(e) {
if (e.which == 32) {
var count = this.value.split(' ').length;
if (count > 2) {
e.preventDefault();
}
}
});
Use event.preventDefault(); with keydown (as suggested by the comments)
Demo: http://jsfiddle.net/wTvmz/
jQuery('#Txt_Report').keydown(function (event) {
if (event.which == 32) {
count = jQuery('#Txt_Report').val().split(' ').length;
if (count > 2) {
event.preventDefault();
}
}
});
Set the disabled attribute to disabled.
jQuery('#Txt_Report').keyup(function (event) {
if (event.which == 32) {
count = jQuery('#Txt_Report').val().split(' ').length;
if (count > 2) {
/////////////
//How can I stop entering text in txt_report anymore?
/////////////
jQuery('#Txt_Report').attr('disabled', 'disabled');
});
}
}
Ref: http://www.w3schools.com/tags/att_input_disabled.asp
Why not utilize "keypress" and return false?
http://jsfiddle.net/kW9tF/
$('#txt').keypress(function (event) {
return false;
});
Updated code example: http://jsfiddle.net/kW9tF/1/
$('#txt').keypress(function (event) {
var count = $(this).val().split(' ').length;
if (count > 2) {
return false;
};
});

Categories

Resources