Rows and column limit in textarea field HTML - javascript

In textarea field i have to implement following restrictions
1. textarea rows limit is 6
2. textarea cols limit is 20
3. if any row exceeded 20 length that row will split in two rows if row available
My Code:
function limitTextareaLine(e) {
if (e.keyCode == 13
&& $(this).val().split("\n").length >= $(this).attr('rows')) {
return false;
}
var result = "";
var textArray = $(this).val().split("\n");
alert(textArray.length);
for (var i = 0; i < textArray.length; i++) { //Unable to iterate loop
if (textArray[i].length > 5) {
alert('aaa');
if (textArray.length == 6) {
alert("nnnnn");
return false;
}
result += textArray[i] + "\n";
} else {
result += textArray[i];
}
alert(textArray[i])
}
for ( var line in textArray) {
}
alert(result);
$(this).val(result);
}
$(function() {
$('textarea.limited').keydown(limitTextareaLine);
});
<textarea rows="6" cols="20" class="limited"></textarea>
In above code loop is not working. Only first line will iterate.
Please suggest if there is any better way to do this.
My requirement is textarea filed have max 6 lines and each line have max char is 20. if any line exceeded the max char limit the split into two lines if max line limit is available.

If I understood it right, this may be what you're looking for.
function limitTextareaLine(e) {
const newLine = /\r*\n/g;
const value = e.target.value;
const newLines = (value.match(newLine) || []).length;
const lines = value.split(newLine);
//enter
if (e.keyCode === 13 && lines.length >= e.target.rows) {
e.preventDefault();
return;
}
const lineNo = value.substr(0, e.target.selectionStart).split(newLine).length - 1;
//backspace
if (e.keyCode === 8 && ~value.charAt(e.target.selectionStart - 1).search(newLine)) {
if (lines[lineNo].length + lines[lineNo - 1].length <= e.target.cols) return;
e.preventDefault();
return;
}
//del
if (e.keyCode === 46 && ~value.charAt(e.target.selectionStart).search(newLine)) {
if (lines[lineNo].length + lines[lineNo + 1].length <= e.target.cols) return;
e.preventDefault();
return;
}
if (e.key.length > 1) return;
if (value.length < e.target.cols) return;
if (lines[lineNo].length > e.target.cols - 1) {
if (lines.length < e.target.rows) {
const col = (e.target.selectionStart - newLines) / lines.length;
let p1 = value.substr(0, e.target.selectionStart);
if (col === e.target.cols) {
p1 += '\r\n' + String.fromCharCode(e.keyCode);
} else {
p1 += String.fromCharCode(e.keyCode) + '\r\n';
}
e.target.value = p1 + value.substr(e.target.selectionStart, value.length);
e.target.selectionStart = p1.length - 1;
e.target.selectionEnd = p1.length - 1;
}
e.preventDefault();
return;
}
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('textarea.limited').addEventListener('keydown', limitTextareaLine);
});
.limited {
width: 200px;
height: 200px;
}
<textarea cols="3" rows="4" class="limited"></textarea>
I want to say that I'm totally unhappy with this code and I'm pretty sure there are some more maintainable and elegant way of doing something like this.
Still, I think you can work with this as an example of how you could do what you want.

Related

char counter doesn't work with paste event

I have written a code bellow for counting the character inside text box.
the code is working just fine the only problem with it is when i past a text into the text box i have to press any key so system start to count.
Could you please help me sort this problem
function GetAlhpa(text) {
var gsm = "#£$¥èéùìòÇØøÅåΔ_ΦΓΛΩΠΨΣΘΞ^{}\[~]|€ÆæßÉ!\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà";
var i = 0;
while (i <= String(text).length) {
if (gsm.indexOf(String(String(text).charAt(i))) == -1 && (String(text).charCodeAt(i) != 32) && (String(text).charCodeAt(i) != 27) && (String(text).charCodeAt(i) != 10) && (String(text).charCodeAt(i) != 13)) {
UniCodestring = " Unicode ";
Countsms = 70;
if ($('#SndSms_Message').val().length > 70)
Countsms = 67;
return;
}
i++;
}
Countsms = 160;
UniCodestring = "";
if ($('#SndSms_Message').val().length > 160)
Countsms = 153;
}
var Countsms = 160;
var UniCodestring = "";
var CounterSmsLen = 0;
var Two = "|^€{}[]~";
function GetCountSms() {
document.getElementById('SndSms_Message').addEventListener('input', function (e) {
var target = e.SndSms_Message,
position = SndSms_Message.selectionStart;
ConvertGreek();
CounterSmsLen = $('#SndSms_Message').val().length;
GetAlhpa($('#SndSms_Message').val());
var i = 0;
while (i < String(Two).length) {
var oldindex = -1;
while (String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) > -1) {
//if ( String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i))) > -1){
CounterSmsLen += 1;
oldindex = String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) + 1;
console.log(i);
}
i++;
}
SndSms_Message.selectionEnd = position; // Set the cursor back to the initial position.
});
if ($('#SndSms_Message').val().length == 0)
CounterSmsLen = 0;
$('#SndSms_Count').html(' ' + CounterSmsLen + ' Characters' + UniCodestring + ' <br /> ' + Math.ceil(CounterSmsLen / Countsms) + ' Sms');
countsmsnumber=Math.ceil(CounterSmsLen / Countsms);
}
var greekchar = "ΑΒΕΖΗΙΚΜΝΟΡΤΥΧ";
var englishchar = "ABEZHIKMNOPTYX";
function ConvertGreek() {
var str = $('#SndSms_Message').val();
var i = 0;
while (i < String(greekchar).length) {
str = str.replace(new RegExp(String(greekchar).charAt(i), 'g'), String(englishchar).charAt(i));
i++;
}
$('#SndSms_Message').val(str);
P.S.
If i paste the number into the text box it will count it correct but if i paste character it wont count them..
You need keyup change event in order to handle paste event.
document.getElementById('SndSms_Message').addEventListener("keyup", function() {
//your code here
});
example

Format Input to 2 Decimals while Typing HTML/Javascript

How can I create an input field for currency? I'm looking for it to work as follows:
Initial: 0.00
Type "1": 0.01
Type "2": 0.12
Type "5": 1.25
I'm pretty new with web design, so I'm looking for a simpler solution. I saw a similar question & answer to this question with an Angular solution, but I'm unsure how to implement that into my HTML project. I have a simple folder with HTML files in it. Thanks!
A little tricky
Working Demo
document.getElementById("demo").onkeydown = function (e) {
//console.log(e.keyCode);
if (e.keyCode != 37 && e.keyCode != 39 && e.keyCode != 8 && e.keyCode != 46)
e.preventDefault();
if (e.keyCode == 8 || e.keyCode == 46) {
//If already key down (backspaceOrDel=1) then no affect
if (backspaceOrDel == 1)
e.preventDefault();
else
backspaceOrDel = 1;
return;
}
if (e.keyCode < 48 || (e.keyCode > 57 && e.keyCode <96) || e.keyCode > 105 )
return;
try {
var val = this.value;
var val1 = 0;
if (val == 0) {
val1 = e.key / 100;
}
else {
//very tricky. We needed val1=val*10+e.key but it does not
//work correctly with floats in javascript.
//Here you have to different than android in logic
var val1 = parseFloat(val) * 1000;
val1 += parseFloat(e.key);
val1 = val1 / 100;
}
val1 = val1.toFixed(2);
if (!isNaN(val1))
this.value = val1;
}
catch (ex) {
alert("Invalid Amount");
}
};
<style>
.amount_tendered {
text-align: right;
font-size: 24px;
width: 200px;
}
</style>
<form>
<input class="amount_tendered" id="text" type="number" min="0" value="0.00" onkeyup="formatNum(this);" onclick="this.select(); activated();">
</form>
<script type="text/javascript">
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
function formatNum(obj){
var str = obj.value;
switch (true){
case str.length==1:
str = '0.0' + str;
break;
case str.length==3:
str = '0' + str;
}
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "." && (str.length - i)!=3) indices.push(i);
}
for(var i=0; i<indices.length;i++) {
str = str.replace('.','');
}
indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === ".") indices.push(i);
}
if (indices.length==0){
str = str.splice(str.length-2, 0, ".");
}
if (str[0]=='0' && str[1]!='.'){
str = str.replace('0','');
}
obj.value = str;
}
</script>

Synchronous input update with selected digit in HTML/JavaScript

I'm trying to implement a customised input that can use left or right arrow key to select the digit and use up/down arrow key to increment/decrement the digit. Here's the code in jsfiddle: http://jsfiddle.net/uk5t3z4d/48/. However, I have two problems:
I cannot add digit using the number pad, the input always stays at X.XX
When I use another function I wrote (parseLocalFloat which is commented out), the output stops displaying anything, and I cannot use the left and right key to select the digit etc.
How can I overcome these two issues? Please shed a light on me, thanks!
HTML
<div class="display" id="out"></div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>
JavaScript
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
function parseLocalFloat(num) {
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
var inputBox = document.getElementById('in');
//var inputBox = parseLocalFloat(document.getElementByID('in').value);
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = inputBox.value;
}
$('#in').on("keydown", function(e){
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if(curPos !== endPos) {
createSelection(this, curPos, curPos+1);
}
// get the position
if(e.keyCode == 37){
curPos--;
gotCode=true;
}
if(e.keyCode == 39){
curPos++;
gotCode=true;
}
var before = $(this).val().substring(0,curPos);
var after = $(this).val().substring(curPos+1);
var cur = Number($(this).val().substring(curPos, curPos+1));
// avoid adding extra stuff
if(curPos < $(this).val().length) {
if(e.keyCode == 38) {
cur++;
if(cur > 9) cur = 0;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
if(e.keyCode == 40) {
cur--;
if(cur < 0) cur = 9;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
}
if(!gotCode) {
e.preventDefault();
return false;
}
var field = this;
window.setTimeout(function(){
createSelection(field, curPos, curPos+1);
}, 10);
});
as for the "get number keys to work":
as stated you need to add the keys you want to support:
if(e.keyCode >= 48 && e.keyCode <= 57) {
var num = e.keyCode - 48; // 0=48; 9=59
$(this).val(before + '' + num + '' + after);
gotCode = true;
e.preventDefault(); // otherwise a new number is added as well
}
(this needs to come before the if (!gotCode) ... )
as for the customFloat: the the response from Moishe
For #1:
if(!gotCode) {
e.preventDefault();
return false;
}
ensures that if gotCode is false the default event (which in this case is the default keydown event) will not occur.
gotCode only seems to be true if keyCode is equal to 37, 38, 39, or 40 (the arrow keys). You are essentially preventing the other keys (like number keys) from having any effect on the textBox.
You probably would like to enable the number keys (when shift or caps aren't on) and number pad keys.
Additionally, you may want to check that the cur is a number (and not .) before attempting to increment or decrement its value.
You could do:
var isNumberKey = (
( e.keyCode >= 48 //is more than or equal to 0 key
&& e.keyCode <= 57 //is less than or equal to 9 key
&& !e.shiftKey) //shift key or cap key not on
|| ( e.keyCode >= 96 //more than or equal to 0 key in number pad
&& e.keyCode <= 105)); //less than or equal to 9 key in number pad
if(!gotCode && !isNumberKey) { //not arrow key or number key
console.log(e);
e.preventDefault();
return false;
}
For #2:
var inputBox = parseLocalFloat(document.getElementByID('in').value);
is setting inputBox to whatever parseLocalFloat returns which happens to be a number.
This is problematic because you then attempt to attach a keyUp event to that number instead of the inputBox:
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = inputBox.value;
}
You may want to instead call parseLocalFloat on the number and set the out textBox's value to that:
var inputBox = document.getElementById('in');
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = parseLocalFloat(inputBox.value);
}
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
function parseLocalFloat(num) {
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
var inputBox = document.getElementById('in');
// var inputBox = parseLocalFloat(document.getElementByID('in').value);
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = parseLocalFloat(inputBox.value);
}
$('#in').on("keydown", function(e){
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if(curPos !== endPos) {
createSelection(this, curPos, curPos+1);
}
// get the position
if(e.keyCode == 37){
curPos--;
gotCode=true;
}
if(e.keyCode == 39){
curPos++;
gotCode=true;
}
var $thisVal = $(this).val();
var before = $thisVal.substring(0,curPos);
var after = $thisVal.substring(curPos+1);
var cur = Number($thisVal.substring(curPos, curPos+1));
// avoid adding extra stuff
if(curPos < $thisVal.length && !isNaN(cur)) {
if(e.keyCode == 38) {
cur++;
if(cur > 9) cur = 0;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
if(e.keyCode == 40) {
cur--;
if(cur < 0) cur = 9;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
}
var isNumberKey = ((e.keyCode >= 48 && e.keyCode <= 57 && [16, 20].indexOf(e.keyCode) == -1 && !e.shiftKey) || (e.keyCode >= 96 && e.keyCode <= 105));
if(!gotCode && !isNumberKey) {
console.log(e);
e.preventDefault();
return false;
}
var field = this;
window.setTimeout(function(){
createSelection(field, curPos, curPos+1);
}, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display" id="out"></div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>

Nothing happens after Prompt

Sorry, I wasn't clear enough. I need it to list all the numbers from 0 to the number inputted by the prompt into the HTML. I made some suggested changes but now I only get the result for the specific number inputted, not all the numbers up to that number. I am just starting out so please be gentle. Thanks!
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for(var i = 0; i <= number; i++) {
if ( i %15 == 0) {
result = "Ping-Pong";
}
else if (i %5 == 0) {
result = "Pong";
}
else if (i %3 == 0) {
result = "Ping";
}
else {
result = number;
}
document.getElementById("show").innerHTML = result;
};
});
You can do either:
for(var i = 0; i <= number; i++) {
var digit = number[i]; // or any other assigment to new digit var
if ( digit % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
or
if ( number % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
Problem is you did nothing after the return keyword. Also you didn't declared variable as digit. I hope this is what you are looking for.
With loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for (var i = 0; i <= number; i++) {
if (i % 15 == 0) { // replaced `digit` with `i`
result = "Ping-Pong";
} else if (i % 5 == 0) {
result = "Pong";
} else if (i % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Without loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
if (number % 15 == 0) { // replaced `digit` with `number`
result = "Ping-Pong";
} else if (number % 5 == 0) {
result = "Pong";
} else if (number % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Ok, I figured it out. For future reference, this is what I was trying to do:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var i
var text = "";
for(i = 1; i <= number; i++) {
if ( i %15 == 0) {
text += "<br>" + "Ping Pong" + "<br>";
}
else if (i %5 == 0) {
text += "<br>" + "Pong" + "<br>";
}
else if (i %3 == 0) {
text += "<br>" + "Ping" + "<br>";
}
else {
text += "<br>" + i + "<br>";
}
};
document.getElementById("show").innerHTML = text;
});

Javascript: Mathfloor still generating a 0

In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.

Categories

Resources