wordwrap for textarea using javascript or jquery - javascript

I need functionality that textarea should contain max 5 lines and
each line should contain max 15 chars, when user writes 2 words
e.g. 123456 123456789 and if that line char limit exceeds 15, then
it should bring the 2nd word in next line along with \n char in first line
(means 123456 will be in first line along with \n and 123456789 will be in 2nd)
,
I need to maintain \n(replacing <br>) in my db for some reasons.
i wrote this code, which gives fuzzy result in some conditions
<textarea onkeypress="charCountTextarea('txt1',event,'75','14')" id="txt1"></textarea>
var countLines=0;
var newLines;
function charCountTextarea(textAreaId,e,limit,lineLen)
{
newLines = $("#"+textAreaId).val().split("\n").length;
var t = $("#"+textAreaId)[0];
var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;
//console.log("new lines"+lineIndex);
if(newLines >= 5 && $("#"+textAreaId).val().split("\n")[lineIndex].length>lineLen)
{
if( e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
{
e.preventDefault();
return false;
}
}
else
if($("#"+textAreaId).val().split("\n")[lineIndex].length>=lineLen) // which will count the total line char condition
{
console.log($("#"+textAreaId).val().split("\n")[lineIndex][lineLen-1]);
if($("#"+textAreaId).val().split("\n")[lineIndex][lineLen-1].indexOf(" ")==-1 && e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && lineIndex != 4 && newLines<5)
{
// to bring the word in next line
var str = $("#"+textAreaId).val(), replacement = '\n';
str = str.replace(/ ([^ ]*)$/,replacement+'$1');
$("#"+textAreaId).val(str);
}
else
if(e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && lineIndex!=4 && newLines<5)
{
// to insert next line
insertTextAtCaret(document.getElementById(textAreaId), "\n");
}
}
if(e.keyCode == 13 && newLines >= 5)
{
//linesUsed.css('color', 'red');
e.preventDefault();
return false;
}
}

function charCountTextarea(textAreaId,e,limit,lineLen)
{
var code = e.charCode || e.keyCode;
newLines = $("#"+textAreaId).val().split("\n").length;
var t = $("#"+textAreaId)[0];
var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;
console.log('val t :'+$("#"+textAreaId).val()+' line index : '+lineIndex+' new lines '+newLines);
if(lineIndex == 10 && $("#"+textAreaId).val().split("\n")[lineIndex].length>(lineLen+1) && code!=8 && code!=46 && code!=33 && code!=34 && code!=35 && code!=36 && code!=37 && code!=38 && code!=39 && code!=40)
{
$("#"+textAreaId).val(($("#"+textAreaId).val()).substring(0, $("#"+textAreaId).val().length - 1));
alert('You are reached to limit');
return false;
}
if(lineIndex<5)
{
$("#"+textAreaId).val($("#"+textAreaId).val().wordWrap(lineLen, "\n", 0));
}
var countLine1 = $("#"+textAreaId).val().split("\n")[0].length;
if($("#"+textAreaId).val().split("\n")[lineIndex].length>lineLen) // which will count the total line char condition
{
console.log("In condition : ");
if(code!=8 && code!=46 && code!=33 && code!=34 && code!=35 && code!=36 && code!=37 && code!=38 && code!=39 && code!=40)
{
// to insert next line
insertTextAtCaret(document.getElementById(textAreaId), "\n");
}
}
}

You can not know if the input will be fed using keyboard. I could just use the mouse to paste a text there.
I would rely on a function that would constantly check the input and take the action you want, which I would execute using the setInterval() function once the textarea is focused, which then gets cleared using clearInterval() once the textarea loses focus.
And this function would use a RegExp to process the input and split it into necessary lines.
EDIT: Here's what I mean.
$('body').on('focus','#txt1',function(e) {
$(this).data('int',setInterval(checkInput,1));
}).on('blur','#txt1',function(e) {
clearInterval($(this).data('int'));
$(this).removeData('int');
});
function checkInput() {
var val = $('#txt1').val();
// process val here
$('#txt1').val(val);
}

Related

missing ) after argument list when creating a variable right after a for statement

I am trying to create the Bagel game and keep getting missing ) after argument list when I try to create the guess variable right after the for statement. Can someone tell me how to fix this?
alert('Lets play the bagel game! If you can guess my three digit number (with each digit being unique) within 20 turns, then you win! I will only provide you with three hints. Pico, which means one digit is correct, but in the wrong position. Fermi, which means one digit is correct and in the right position. Bagels, which means no digits are correct');
//computer generates number
function numberRange(){
var number = Math.round(Math.random()*1000);
var num =number.toString();
if (number <= 100 || number == 1000){
numberRange();
}
else if (num[0] == num[1] || num[0] == num[2] || num[1]==num[2]){
numberRange();
}
else if (number == undefined || num == undefined){
numberRange();
}else{
var numSave = JSON.stringify(num);
sessionStorage.setItem('number',numSave);
}}
numberRange();
var numGet = sessionStorage.getItem('number');
var numUse = JSON.parse(numGet);
//game start
for (i=1;i<21;i++){
var validNumber = /\d{3}/;
var guess = prompt('Turn ' + i ': Guess a number!');
while (validNumber.test(guess) == false) {
alert('Put in a three digit number!');
var guess = prompt('Turn ' + i ': Guess a number!');
}
if (validNumber.test(guess)){
var guessNum = guess.toString();
if (guessNum[0] == numUse[0] && guessNum[1] && numUse[1] && guessNum[2] == numUse[2]){
alert('Congratulations! You win!');
break
}
else if ((guessNum[0] == numUse[0] || guessNum[1] == numUse[1] || guessNum[2] == numUse[2]) && (guessNum[0] == numUse[1] || guessNum[0] == numUse[2] || guessNum[1] == numUse[0] || guessNum[1] == numUse[2] || guessNum[2] == numUse[0] || guessNum[2] == numUse[3])){
alert('Pico and Fermi!');
}else if(guessNum[0] == numUse[1] || guessNum[0] == numUse[2] || guessNum[1] == numUse[0] || guessNum[1] == numUse[2] || guessNum[2] == numUse[0] || guessNum[2] == numUse[3]){
alert('Pico!');
}else if (guessNum[0] == numUse[0] || guessNum[1] == numUse[1] || guessNum[2] == numUse[2]){
alert('Fermi!');
}else (guessNum[0] != numUse[0] && guessNum[0] != numUse[1] && guessNum[0] != numUse[2] && guessNum[1] != numUse[0] && guessNum[1] != numUse[1] && guessNum[1] != numUse[2] && guessNum[2] != numUse[0] && guessNum[2] != numUse[1] && guessNum[2] != numUse[2]){
alert('Begels!');
}
}
}
I see several issues.
var guess = prompt('Turn ' + i ': Guess a number!');
is missing + after i '
It should be like this:
var guess = prompt('Turn ' + i + ': Guess a number!');
You're also defining the same variable name twice inside the for scope, just do guess = prompt('Turn ' + i ': Guess a number!'); inside the while loop.
I didn't check the rest of the code, but this should get you started.
you seem to have missed a "+" as a part of string concatenation.
prompt('Turn ' + i+': Guess a number!');
instead of
prompt('Turn ' + i': Guess a number!');
What the other folks said (there are 2 places you need + signs, l#s 25, 28) and your final else needs an if before the test clause (L# 41). After that it should at least run. A few other comments:
only var a variable the first time it is declared.
look into switch statements and use them when you have more than 2 options and a default.
try to break up long lines (as in add line feeds) and keep all the code on the screen. Javascript doesn't care at all about white space so use it. Far easier to debug things when you can see it all.
a good editor will find this stuff for you. There are a lot of free ones (Atom, Komodo) that do a decent job of syntax highlighting and error detection.

Insert X after 15 character in input mask

(XXX) XXX-XXXX xXXXX
I want insert a X symbol after every 15th character in input. I have a Business Phone input box. When a user is typing and reaches each 15th character, then jQuery will insert a hyphen (X).
For example: (999) 999-9999 x9999
I'm trying some codes and i think i'm so close to correct code but i have some problems. Here is my code sample;
$(document).delegate('#businessPhone', 'keyup', function(e) {
var Textlength = $(this).val();
console.log(Textlength.length);
if (Textlength.length >= 14) {
//alert("if"+Textlength.length);
$("#businessPhone").mask("(999) 999-9999 x9999");
return false;
} else {
//alert("else"+Textlength.length);
$("#businessPhone").mask("(999) 999-9999");
}
});
Code is working fine as aspected if user complete enter all characters.
But problem is user wants to remove characters the characters did not delete if character length reach 14 .
try this
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
if ($phone.val().length === 15) {
$phone.val($phone.val() + ' x');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
<form id="example-form" name="my-form">
<label>Phone number:</label><br />
<!-- I used an input type of text here so browsers like Chrome do not display the spin box -->
<input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX" /><br /><br />
<input type="button" value="Submit" />
</form>

Validation to check whether the textbox value is changed or not

I want a validation that only allows alphanumeric characters,backspace,delete,space and special characters which can change the text box value from Kyeboard.I have tried like
$('#profile_pstate').on('keypress',function(e1){
var cntry_key = e1.which;
if(cntry_key == 8 || cntry_key == 46 || cntry_key == 32 || (cntry_key >= 48 && cntry_key <= 57) || (cntry_key >= 65 && cntry_key <= 90)) {
// For Backspace, Delete, Space, Numbers and Alphabets
alert('success');
}
});
But for the special characters how can I add them.If I add them manually they are not in a proper range like alphabets and numeric.Could you please suggest me a way to do it or even a correct way to do the validation.
You can do like this for special characters
function nospecialChars(field) {
var val = document.getElementById(field);
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < val.value.length; i++) {
if (iChars.indexOf(val.value.charAt(i)) != -1) {
alert("Special Characters are not allowed");
return false;
}
}
}
On page textbox change method call function
<input type="text" id="txt" onkeyup="validate(this.id)" />
Try RegExp, below example allows alpha-numeric & spaces only:
$(function() {
$('#profile_pstate').on('input', function() {
this.value = this.value.replace(/[^\da-zA-Z\s]/g, '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="profile_pstate" />
I have tried like
$('#profile_country').on('keypress',function(e1){
var cntry_key = e1.which;
var cntry_key_code = e1.keyCode;
if( (cntry_key_code == 0 && cntry_key > 0 && !e1.ctrlKey) || (cntry_key == 0 && cntry_key_code == 46) || (cntry_key == 8)
|| (e1.ctrlKey && cntry_key == 120) || (e1.ctrlKey && cntry_key == 118)
|| (e1.ctrlKey && cntry_key == 86) || (e1.ctrlKey && cntry_key == 88)) {
$('#profile_pstate').val('');
}
});
And it is working fine with Alpha-Numeric, Special characters, Space, Backspace and Delete and also control events like ctrl+A AND only works for cut(ctrl+x) and paste(ctrl+v).

Disable first character in textbox

I have a textbox and it contain a value "Given Name". I want to disable first character of a textbox so that user cannot change the First Charcter in textbox by using backspace or any other means.
For Example: suppose textbox contains the value "Given Name". I want that user cannot change the First character "G" by using backspace or any other means.
<input type="text" id="nameId" onkeydown="validate(this.val)"/>
Below is javascript function:
function validate2(val) {
// have no idea how to do.
}
I have no idea how to do it in Javscript or Jquery.
You could do like follow :
$("#nameId").on("keydown", function(e) {
// if user writes a char at index === 0 that is not an arrow or HOME or END
if (($(this).get(0).selectionStart === 0 && (e.keyCode < 35 || e.keyCode > 40))
// or if user tries to erase first char
|| ($(this).get(0).selectionStart === 1 && $(this).get(0).selectionEnd === 1 && e.keyCode === 8)) {
// don't write the character
return false;
}
});
// prevent right click
$("#nameId").bind("contextmenu", function(e) {
e.preventDefault();
});
JSFIDDLE
Wasn't planning on answering, leaving it with the comment, but after seeing the other answers thought I might have a quick go at it after all:
The html:
<input type="text" id="nameId" value="Given Name" onkeydown="save(this,event)" onkeyup="restore(this,event)" onchange="restore(this,event)"/>
The javascript:
function restore(el,event) {
if(el.value.length == 0){
el.value = el.dataset.value.substr(0,1);
}else{
el.dataset.value = el.value;
}
}
function save(el,event) {
var key = event.which || event.charCode || event.keyCode;
if((key === 8 && el.value.length === 1)
|| (key === 46 && el.selectionStart == 0 && el.value.length === 1)){
event.preventDefault();
}
if(el.value.length > 0){
el.dataset.value = el.value;
}
}
The approach was to not mess around too much with preventing the deletion of the actual character (just the very bare basics) and instead ensure that if somebody deletes the first character to always restore it somehow. It creates code that's easy to comprehend and maintain, yet works quite neatly. A fiddle can be found here as well. Do note though that event.which is not the most cross browser consistent interface, so either use jQuery for that or check in other browsers before using it in production. Edited it in a way that should work cross browser including older browsers.
Here's mine version.
Html
<input type="text" id="nameId" value="Given Name" />
JS
var lastentry = '';
$("#nameId").on("keyup", function(e) {
var targetValue = $(e.currentTarget).attr('value');
var targetValueLength = targetValue.length;
var inputValue = this.value;
if(checkChanges(targetValueLength, targetValue, inputValue))
this.value = targetValue + lastentry;
else
lastentry = this.value.slice(targetValueLength)
});
function checkChanges(targetValueLength, targetValue, inputValue)
{
for(var i = 0; i < targetValueLength ; i++)
{
if(targetValue[i] != inputValue[i])
return true;
}
return false;
}
Demo
You can try this:-
<input type="text" id="nameId" value="Given Name" onkeydown="validate(this.value,event)"/>
<script>
function validate(val,event) {
// have no idea how to do.
if(event.target.selectionStart != undefined && (event.which === 46 ||event.which === 8)){
var startPos = event.target.selectionStart,
endPos = event.target.selectionEnd;
console.log(startPos,endPos);
if(startPos === 0 && startPos != endPos){
var restPart = val.slice(endPos,val.length);
if(restPart){
val = val[0].concat(restPart);
} else{
val = val[0]
}
event.target.value = val;
event.preventDefault();
} else if(startPos === 0 && startPos === endPos && event.which === 46){
event.preventDefault();
} else if(startPos === 1 && event.which === 8){
event.preventDefault();
}
}
}
</script>
Hi use this it do not allow to delete first character ,
$(document).keydown(function(e)
{
var value = $('#nameId').val().length;
if ( e.keyCode == 8 && value < 2)
e.preventDefault();
});

Don't want decimal value in the input field

I dont want to allow the decimal values in text box.. I have written the code but it works only if you remove the whole value and then reinsert it..
My issue is when I try to edit the existing value it take the decimal numbers..
Here's the jsfiddle. This is code for reference:
HTML
<input id="Amt" type="text" value="$78.00">
jQuery
$(document).ready(function () {
$("#Amt").keydown(function (e) {
if ((!e.shiftKey && !e.ctrlKey && !e.altKey) && ((e.keyCode >= 48 && e.keyCode <= 57) ||
(e.keyCode >= 96 && e.keyCode <= 105))) {
}
else if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 39 &&
e.keyCode != 9) {
e.preventDefault();
}
});
$("#Amt").keyup(function (e) {
var value = $(this).val();
var newValue = parseFloat(value).toFixed(2);
if (!isNaN(newValue)) {
$(this).val(newValue);
$(this).caret(newValue.length - 3, newValue.length - 3);
}
});
});
You can use string methods to chop out the decimal and re-append '.00' if you want to keep this format.
$("#Amt").blur(function (e) {
var value = this.value.replace(/\$/g,"");
var dotPos = value.indexOf(".");
var dollars = dotPos>-1?value.substring(0,dotPos):value;
$(this).val(dollars+".00");
});
$("#Amt").blur();
http://jsfiddle.net/ZUj8M/14/
I would go about it in a completely different way, just prevent the decimal from getting there in the first place. http://jsfiddle.net/ZUj8M/7/
$(document).ready(function () {
var timer;
$("#Amt").on("keydown paste input",function (e) {
var el = this,
origval = this.value;
clearTimeout(timer);
timer = setTimeout(function () {
if (origval != el.value && /\./.test(el.value)) {
el.value = origval;
alert("Decimals are not allowed in this field.");
}
}, 0);
});
if (/\./.test($("#Amt").val())) {
$("#Amt").val($("#Amt").val().replace(/\./g,""));
}
});
alternatively you could instead of undoing the change, simply remove the decimal.
// el.value = origval;
// alert("Decimals are not allowed in this field.");
el.value = el.value.replace(/\./g,"");
why not parsing the given value to Integer?
var newValue = parseInt(floatValue, 10);
then allow the users to insert a dot "." and on .blur()-event you can parse the float to int...
$("#Amt").blur(function() {
$this.val(parseInt(jQuery(this).val(), 10));
});

Categories