Text input allows for more than 3 characters - javascript

I have an input where the user can enter initials. The input has a max length of 3.
I have the following js
personaliseShirt.plInitials = function () {
console.log('pressed');
var inputPL = $('.max-length_3');
$(inputPL).on('keyup', function () {
var max = 3;
console.log(inputPL.val.length);
if (inputPL.val.length > max) {
inputPL.val = inputPL.value.substring(0, max);
}
})
}
My issue is that the first input field seems to stop the user from entering more than 3 characters but if the user has multiple, then after the first input the rest allow for more than 3 :/
HTML for input field
<input onkeyup="this.value = this.value.toUpperCase();" pattern="[A-Za-z]+" maxlength="3" type="text" class="form-control input-block-level defaultY? max-length_3" max="3" value="" placeholder="Enter Player Initials" name="player_2_9_6" id="player_2_9_6">
Any help or suggestions would be great
Thanks in advance!

Your variable inputPL is a JQuery array with multiple elements in it. In your keyup handler, you check for the length of this array, which won't work. Use this instead:
personaliseShirt.plInitials = function () {
console.log('pressed');
var inputPL = $('.max-length_3');
$(inputPL).on('keyup', function () {
var max = 3;
var $thisElem = $(this);
console.log($thisElem.val.length);
if ($thisElem.val.length > max) {
$thisElem.val = $thisElem.value.substring(0, max);
}
})
}
Also please check, if your mix-up of val and value is intended, or if you need to use val() instead.

It's working on firefox and chrome. You can use this function for repeated use.
$('input.testinput').on('keyup', function() {
limitText(this, 3)
});
function limitText(field, maxChar){
var ref = $(field),
val = ref.val();
if ( val.length >= maxChar ){
ref.val(function() {
console.log(val.substr(0, maxChar))
return val.substr(0, maxChar);
});
}
}
Demo

Related

2 textbox that copies each other value while typing, but the other textbox has no comma

I'm currently working with 2 textboxes that copies each other values. But the thing is, my 1st textbox has an autocomma. How could I make my 2nd textbox ignore the comma?
For example. My first textbox value is 1,000 then my 2nd textbox
value should be 1000.
HTML
<input type="text" value="" id="textbox1"/>
<input type="text" value="" id="textbox2"/>
Script
//this function is for my autocomma
function updateTextView(_obj){
var num = getNumber(_obj.val());
if(num==0){
_obj.val('');
}else{
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#textbox1').on('keyup',function(){
updateTextView($(this));
});
});
//this function copies the textbox1 values to textbox value 2
$("#textbox1").bind('input', function () {
var stt = $(this).val();
$("#textbox2").val(stt);
});
You modify the function updateTextView as below:
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
$("#textbox2").val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
And then remove the following:
$("#textbox1").bind('input', function () {
var stt = $(this).val();
$("#textbox2").val(stt);
});
In plain JS:
Try the onkeyup() event added to the first textbox. Then replace all commas in the value of the first box with nothing using value.replace(/,/g, ""). And then copy the value of the first input
function update(input) {
var value = input.value.replace(/,/g, "");
document.getElementById("second-textbox").value = value;
}
<input onkeyup="(update(this))" />
<input id="second-textbox" />
to the second.

Very new to Javascript. Can't seem to get 1 function to work in my code (berekenBedrag). Needs to calculate the total

I'm struggling with the same code for days now and it's becoming frustrating.
I checked youtube, google, read in Flanagan but I can't seem to find the answer.
Now, I believe I came to the end of my code but one function I don't get to work.
I need to have 1 input text were the user puts in an amount, presses enter and the total needs to go to input text 2.
After each input, the input from text 1 needs to get emptied.
Everything works except for calculating the total in input text 2.
Thanks for reading and appreciate the help.
This is my code:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="input1"><br><br>
<input type="text" id="input2">
<script>
document.getElementById("input1").addEventListener("keyup", function(e) {
if ( e.keyCode === 13) {
myFunction();
}
});
function myFunction() {
var bedrag = leesInvoer("input1");
document.getElementById("input1").value="";
document.getElementById("input2").value = berekenBedrag(bedrag).toFixed(2) +
" euro";
}
function berekenBedrag(pBedrag) {
var input = document.getElementById("input2");
pBedrag = pBedrag+input;
//This function is wrong but I don't know how to calculate the total from input 1 and 2 together.
return pBedrag;
}
function leesInvoer(invoerId) {
var invoer = document.getElementById(invoerId);
var getal = +invoer.value;
return getal;
}
</script>
</body>
</html>
Put the " euro" outside the input
Parse the number
Disable the other field from accepting input
Use "change" in case they use another input method (tab off, hit "enter" or some other way (click off) etc.
Reset the input value where you got it (I used null but that is a style choice)
document.getElementById("input1")
.addEventListener("change", function(e) {
//if (e.keyCode === 13) {
myFunction();
//}
});
function myFunction() {
var bedrag = leesInvoer("input1");
document.getElementById("input2").value = berekenBedrag(bedrag).toFixed(2);
}
function berekenBedrag(pBedrag) {
let input = document.getElementById("input2");
pBedrag = pBedrag + (input.value * 1);
return pBedrag;
}
function leesInvoer(invoerId) {
let invoer = document.getElementById(invoerId);
let getal = !isNaN(parseFloat(invoer.value)) && isFinite(invoer.value) ? parseFloat(invoer.value) : 0;
invoer.value = null;
return getal;
}
<div><input type="text" id="input1"></div>
<div>
<input type="text" id="input2" disabled><span> euro</span></div>
You can use a global variable to store the total (which starts at 0) and add the value of the input after converting to a number (using the unary plus operator) each time.
document.getElementById("input1").addEventListener("keyup", function(e) {
if (e.keyCode === 13) {
myFunction();
}
});
let total = 0;
function myFunction() {
var bedrag = +document.getElementById("input1").value;
total += bedrag;
document.getElementById("input1").value = "";
document.getElementById("input2").value = total.toFixed(2) +
" euro";
}
<input type="text" id="input1"><br><br>
<input type="text" id="input2">

if input field is not a number OR not empty replace with a number

I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle

Comparing two input fields

I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions.
<script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>
<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>
A tidy way to do it which is easy to read:
var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;
if (firstInput === secondInput) {
// do something here if inputs are same
} else if (firstInput > secondInput) {
// do something if the first input is greater than the second
} else {
// do something if the first input is less than the second
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Here's a suggestion/hint
if (Math.abs(v1 - v2) <= 1) {
alert("can't have duplicate!");
return false;
}
And here's the jsfiddle link, if you want to see the answer
Give them both IDs.
Then use the
if(document.getElementById("first").value == document.getElementById("second").value){
//they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
//first is more than second
}
and so on.

Pasting multiple numbers over multiple input fields

I've got a form on my site using 6 input fields. The site visitor simply enters a 6 digit code into these 6 boxes. The thing is that they'll get the 6 digit code and it would be ideal to allow them to simply copy the 6 digit code we send them into these input fields by simply putting pasting into the first input field and having the remaining 5 digits go into the remaining 5 input fields. It would just make it much easier than having to manually enter each digit into each input field.
Here's the code we're currently using, but it can easily be changed to accomplish what is described above:
<input type="text" maxlength="1" class="def-txt-input" name="chars[1]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[2]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[3]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[4]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[5]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[6]">
I saw a posting similar to this here: Pasting of serialnumber over multiple textfields
But it doesn't have the solution I'm looking for. Ideally this could be pulled off using jQuery or plain JavaScript.
Edit
I didn't like the timer solution I used in the paste event and the complexity of just using the input or paste event.
After looking at this for a while I added a solution which uses a hybrid between the 2.
The code seems to do all that is required now.
The Script:
var $inputs = $(".def-txt-input");
var intRegex = /^\d+$/;
// Prevents user from manually entering non-digits.
$inputs.on("input.fromManual", function(){
if(!intRegex.test($(this).val())){
$(this).val("");
}
});
// Prevents pasting non-digits and if value is 6 characters long will parse each character into an individual box.
$inputs.on("paste", function() {
var $this = $(this);
var originalValue = $this.val();
$this.val("");
$this.one("input.fromPaste", function(){
$currentInputBox = $(this);
var pastedValue = $currentInputBox.val();
if (pastedValue.length == 6 && intRegex.test(pastedValue)) {
pasteValues(pastedValue);
}
else {
$this.val(originalValue);
}
$inputs.attr("maxlength", 1);
});
$inputs.attr("maxlength", 6);
});
// Parses the individual digits into the individual boxes.
function pasteValues(element) {
var values = element.split("");
$(values).each(function(index) {
var $inputBox = $('.def-txt-input[name="chars[' + (index + 1) + ']"]');
$inputBox.val(values[index])
});
};​
See DEMO
Here is an example of a jquery plugin that does the same thing as the original answer only generalized.
I went to great lengths to modify the original answer ( http://jsfiddle.net/D7jVR/ ) to a jquery plugin and the source code is here: https://github.com/relipse/jquery-pastehopacross/blob/master/jquery.pastehopacross.js
An example of this on jsfiddle is here:
http://jsfiddle.net/D7jVR/111/
The source as of 4-Apr-2013 is below:
/**
* PasteHopAcross jquery plugin
* Paste across multiple inputs plugin,
* inspired by http://jsfiddle.net/D7jVR/
*/
(function ($) {
jQuery.fn.pastehopacross = function(opts){
if (!opts){ opts = {} }
if (!opts.regexRemove){
opts.regexRemove = false;
}
if (!opts.inputs){
opts.inputs = [];
}
if (opts.inputs.length == 0){
//return
return $(this);
}
if (!opts.first_maxlength){
opts.first_maxlength = $(this).attr('maxlength');
if (!opts.first_maxlength){
return $(this);
}
}
$(this).on('paste', function(){
//remove maxlength attribute
$(this).removeAttr('maxlength');
$(this).one("input.fromPaste", function(){
var $firstBox = $(this);
var pastedValue = $(this).val();
if (opts.regexRemove){
pastedValue = pastedValue.replace(opts.regexRemove, "");
}
var str_pv = pastedValue;
$(opts.inputs).each(function(){
var pv = str_pv.split('');
var maxlength;
if ($firstBox.get(0) == this){
maxlength = opts.first_maxlength;
}else{
maxlength = $(this).attr('maxlength');
}
if (maxlength == undefined){
//paste them all!
maxlength = pv.length;
}
//clear the value
$(this).val('');
var nwval = '';
for (var i = 0; i < maxlength; ++i){
if (typeof(pv[i]) != 'undefined'){
nwval += pv[i];
}
}
$(this).val(nwval);
//remove everything from earlier
str_pv = str_pv.substring(maxlength);
});
//restore maxlength attribute
$(this).attr('maxlength', opts.first_maxlength);
});
});
return $(this);
}
})(jQuery);
This shouldn't be too difficult ... add a handler for the paste event on the first input, and then process per the requirement.
Edit
Actually this is much trickier than I thought, because it seems there's no way to get what text was pasted. You might have to kind of hack this functionality in, using something like this (semi-working)... (see the JSFiddle).
$(document).on("input", "input[name^=chars]", function(e) {
// get the text entered
var text = $(this).val();
// if 6 characters were entered, place one in each of the input textboxes
if (text.length == 6) {
for (i=1 ; i<=text.length ; i++) {
$("input[name^=chars]").eq(i-1).val(text[i-1]);
}
}
// otherwise, make sure a maximum of 1 character can be entered
else if (text.length > 1) {
$(this).val(text[0]);
}
});
HTML
<input id="input-1" maxlength="1" type="number" />
<input id="input-2" maxlength="1" type="number" />
<input id="input-3" maxlength="1" type="number" />
<input id="input-4" maxlength="1" type="number" />
jQuery
$("input").bind("paste", function(e){
var pastedData = e.originalEvent.clipboardData.getData('text');
var num_array = [];
num_array = pastedData.toString(10).replace(/\D/g, '0').split('').map(Number); // creates array of numbers
for(var a = 0; a < 4; a++) { // Since I have 4 input boxes to fill in
var pos = a+1;
event.preventDefault();
$('#input-'+pos).val(num_array[a]);
}
});
You're going to have to right some custom code. You may have to remove the maxlength property and use javascript to enforce the limit of one number per input.
As dbasemane suggests, you can listen for a paste event. You can listen to keyup events too to allow the user to type out numbers without having to switch to the next input.
Here is one possible solution:
function handleCharacter(event) {
var $input = $(this),
index = getIndex($input),
digit = $input.val().slice(0,1),
rest = $input.val().slice(1),
$next;
if (rest.length > 0) {
$input.val(digit); // trim input value to just one character
$next = $('.def-txt-input[name="chars['+ (index + 1) +']"]');
if ($next.length > 0) {
$next.val(rest); // push the rest of the value into the next input
$next.focus();
handleCharacter.call($next, event); // run the same code on the next input
}
}
}
function handleBackspace(event) {
var $input = $(this),
index = getIndex($input),
$prev;
// if the user pressed backspace and the input is empty
if (event.which === 8 && !$(this).val()) {
$prev = $('.def-txt-input[name="chars['+ (index - 1) +']"]');
$prev.focus();
}
}
function getIndex($input) {
return parseInt($input.attr('name').split(/[\[\]]/)[1], 10);
}
$('.def-txt-input')
.on('keyup paste', handleCharacter)
.on('keydown', handleBackspace);
I have this code set up on jsfiddle, so you can take a look at how it runs: http://jsfiddle.net/hallettj/Kcyna/

Categories

Resources