Want to limit korean and chinese - javascript

I need to limit input box content based on lang. enter.
For example:-
If a string with Korean characters is input, then the number of permitted characters is 8.
If a string with Chinese characters is input, the number of permitted characters is 5.
If that with English, then 12 characters are permitted.
My code is working well for English characters in IE, Firefox and Chrome. However, this code is not working as expected for Korean and Chinese characters. My code always cuts the length of string to 2 even if i increase the valid length. Please suggest some solution as soon as possible.
I am pasting my code for checking.
<!DOCTYPE html>
<html>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
document.onkeydown=function() {
var text = $('#lang').val();
var hangul = new RegExp("[\u1100-\u11FF|\u3130-\u318F|\uA960-\uA97F|\uAC00-\uD7AF|\uD7B0-\uD7FF]");
var china = new RegExp("[\u4E00-\u9FFF|\u2FF0-\u2FFF|\u31C0-\u31EF|\u3200-\u9FBF|\uF900-\uFAFF]");
// alert(hangul.test(text));
if(hangul.test(text))
{
limit = 8;
//console.log("korean");
limitCharacters('lang', limit , text);
}else if(china.test(text))
{
limit = 5;
//console.log("china");
limitCharacters('lang', limit , text);
}else {
limit = 11;
limitCharacters('lang', limit , text);
}
};
function limitCharacters(textid, limit, text)
{
//alert('here in limit funt.');
var textlength = text.length;
//alert(textlength);
if(textlength > limit )
{
$('#'+textid).val(text.substr(0,limit));
return false;
}else {
$('#'+textid).val(text);
$('#txt').html(text);
return true;
}
}
</script>
<body>
<input type="text" id="lang" />
</body>
</html>

I solved this issue and now it is working fine for me. As per my understanding substring is not supported by IE.
<html>
<title> test</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="http://css-browser-selector.googlecode.com/git/css_browser_selector.js"></script>
<script src="./beta.fix.js"></script>
<script>
var keyFix = new beta.fix('lang');
jQuery(document).ready( function($) {
jQuery('#lang').bind('keyup', checklang);
});
function checklang() {
var textid = jQuery(this).attr("id");
var text = jQuery(this).val();
var hangul = new RegExp("[\u1100-\u11FF|\u3130-\u318F|\uA960-\uA97F|\uAC00-\uD7AF|\uD7B0-\uD7FF]");
var china = new RegExp("[\u4E00-\u9FFF|\u2FF0-\u2FFF|\u31C0-\u31EF|\u3200-\u9FBF|\uF900-\uFAFF]");
// alert(hangul.test(text));
if(china.test(text))
{
limit = 5;
console.log("chiness");
}else if(hangul.test(text))
{
limit = 8;
console.log("korean");
}else {
limit = 11;
console.log("english");
}
jQuery('#'+textid).attr("maxlength", limit);
};
</script>
<body>
<input type="text" id="lang" size="100" />
</body>
</html>

Can you try this:
var hangul = new RegExp("[\u1100-\u11FF|\u3130-\u318F|\uA960-\uA97F|\uAC00-\uD7AF|\uD7B0-\uD7FF]");
var china = new RegExp("[\u4E00-\u9FFF|\u2FF0-\u2FFF|\u31C0-\u31EF|\u3200-\u9FBF|\uF900-\uFAFF]");
$("#lang").on("keypress keyup", function () {
var that = $(this);
var text = that.val();
if (china.test(text)) {
limit = 5;
} else if (hangul.test(text)) {
limit = 8;
} else {
limit = 11;
}
that.attr("maxlength", limit);
if (text.length > limit) that.val(text.substring(0, limit))
});
also on http://jsfiddle.net/sWPeN/1/

Related

Calling a JavaScript function in HTML?

I'm extremely new to JavaScript and HTML so go easy on me. I'm attempting to call a function from my external JavaScript file in my HTML file, but nothing I seem to do allows it to work.
JavaScript Code
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = document.getElementById("len");
function generatePassword(passLength){
// Check to see if selected length is at least 8 characters long
while (trueLength = false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
}
}
// Select random character from things and add to password until desired length is reached.
for(var x = 0; x <= passlength;){
var randomNum=Math.floor(Math.random()*things.length+1);
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<!DOCTYPE html>
<html>
<head>
<title>Password Generator</title>
</head>
<body>
<h1 align="center">Password Generator</h1>
<script type="text/javascript" src="PassGen.js"></script>
<script>
var x = prompt("Enter password length: ")
function generatePassword(x);
</script>
</body>
</html>
The goal is for the user to be prompted to input a password length, then generate a random password which will be alerted to the user and written on screen. However, only the header at the top of the screen is printed.
(I realize that I could just take the function out of the JavaScript file and run it normally, but I kinda wanna leave it like this so I know what to do in the future if I ever run into this situation again.)
Following is the code with Javascript inside <script> tag within HTML document. One thing you should be careful of while writing your javascript code in the HTML file is, to include your javascript code just before the ending tag of body </body>. so it get executed only when your html file is loaded. But if you add your javascript code in the starting ot html file, your JS code will be executed before the file is loaded.
<!DOCTYPE html>
<html>
<head>
<title>Generate Password</title>
</head>
<body>
<h1 align="center">Password Generated will be displayed here</h1>
<p id="password" align="center"></p>
<script>
var PasswordLength = false;
var password = "";
var passwordChoice = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = prompt("Enter password length: ");
var pass = document.getElementById("password");
generatePassword(input);
function generatePassword(passLength){
while (PasswordLength == false){
if (passLength >= 8){
for(var x = 0; x < passLength;x++){
var randomNum=Math.floor(Math.random()*passwordChoice.length+1);
password = password + passwordChoice.charAt(randomNum);
}
PasswordLength = true;
}
else {
passLength = prompt("Password Length must be 8 characters long.");
}
}
pass.innerHTML = password;}
</script>
</body>
</html>
And if you want to have your Javascript code in a separate file, which can be helpful in big programs, then you need to reference that file using <script> tag and this is the way you write it down.
var PasswordLength = false;
var password = "";
var passwordChoice = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = prompt("Enter password length: ");
var pass = document.getElementById("password");
generatePassword(input);
function generatePassword(passLength){
while (PasswordLength == false){
if (passLength >= 8){
for(var x = 0; x < passLength;x++){
var randomNum=Math.floor(Math.random()*passwordChoice.length+1);
password = password + passwordChoice.charAt(randomNum);
}
PasswordLength = true;
}
else {
passLength = prompt("Password Length must be 8 characters long.");
}
}
pass.innerHTML = password;}
<!DOCTYPE html>
<html>
<head>
<title>Generate Password</title>
<script src=""></script>
</head>
<body>
<h1 align="center">Password Generated will be displayed here</h1>
<p id="password" align="center"></p>
</body>
</html>
In your code there are the following problems :
1) Change function generatePassword(x); to generatePassword(x.length);
2) Change trueLength = false to trueLength === false
3) Change for(var x = 0; x <= passlength;){ to for(var x = 0; x < passLength; x++){
passlength => passLength , x<= to x< , insert x++
4) Change Math.floor(Math.random()*things.length+1); to Math.floor(Math.random()*(things.length)+1)
5) insert passLength = passLength.length; to else
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = document.getElementById("len");
var x = prompt("Enter password length: ")
generatePassword(x.length);
function generatePassword(passLength){
// Check to see if selected length is at least 8 characters long
while (trueLength == false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
passLength = passLength.length;
}
}
// Select random character from things and add to password until desired length is reached.
for(var x = 0; x < passLength; x++){
var randomNum=Math.floor(Math.random()*(things.length)+1);
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<h1 align="center">Password Generator</h1>
You can use this code with less complexity :
var trueLength = false, password = "" ;
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var x = prompt("Enter password length: ")
generatePassword(x);
var input = document.getElementById("len");
function generatePassword(passLength){
while ( passLength.length < 9 )
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
for ( var x = 0; x < passLength.length ; x++ ) {
var randomNum = Math.floor ( Math.random() * (things.length)+1 );
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<h1 align="center">Password Generator</h1>
Few things. In order to have something show up in HTML, you will need to select an HTML element in JavaScript. Next, you used 'passlength' instead of 'passLength' in the for loop. Third, when you write function generatepassword it is invalid syntax as Lux said. Lastly, your for loop doesn't go anywhere because you don't have a third expression. Which should be changed to
for(var x = 0; x <= passLength;x++)
Edit: Another thing I forgot was trueLength = false should be changed to trueLength == false or trueLength === false.
With all that said, here's my solution:
<!DOCTYPE html>
<html>
<head>
<title>Password Generator</title>
</head>
<body>
<h1 align="center">Password Generator</h1>
<p align="center"></p>
<!--script type="text/javascript" src="PassGen.js"></script-->
<script>
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
//var input = document.getElementById("len");
var ppass = document.querySelector("p");
function generatePassword(passLength){
while (trueLength == false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
}
}
for(var x = 0; x <= passLength;x++){
var randomNum=Math.floor(Math.random()*things.length+1);
password = password + things.charAt(randomNum);
}
//alert("Your password is: " + password);
//document.write("<h1>Your Password</h1><p>" + password + "</p>");
ppass.textContent = password;}
var x = prompt("Enter password length: ")
generatePassword(x);
</script>
</body>
</html>
What I added was a <p> tag to display the password once it's generated. I use textContent to display it once the password is done generating. And i use document.querySelector to access it.

Making a javascript hangman game and I can't get my function to apply to repeated letters

Everything about the script works great right now unless there's a repeated letter in the word. If so, then it will only display the first of the letters. For example, if the random word is "look" it would display like this "lo k".
Unfortunately the only other related javascript hangman question here was for a script that didn't actually have issues on repeated letters. For reference: how to deal with repeated letters in a javascript hangman game. Can anyone help me get through the repeated letter issue? Thanks!
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-1.11.2.min.js"></script>
<script src="js/jquery-1.11.2.js"></script>
<link rel="stylesheet" href="css/main.css">
<title>Hang a Blue Devil</title>
</head>
<body>
<div class="wrapper">
<h1 class="title">Hangman</h1>
<h2 class="attempt-title">You have this many attempts left: </h2>
<ul class="hangman-word">
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
</ul>
<h3 class="hangman-letters"></h3>
<input class="text-value" type="text" maxlength="1" onchange="setGuess(this.value)">
<button class="text-button" onclick="checkGuess()"></button>
<p class="letters-guessed"></p>
</div>
</body>
<script src="js/hangman.js"></script>
</html>
My JS:
var hangmanWords = [
"the","of","and","a","to","in","is","you","that","it","he",
"was","for","on","are","as","with","his","they","I","at","be",
"this","have","from","or","one","had","by","word","but","not",
"what","all","were","we","when","your","can","said","there",
"use","an","each","which","she","do","how","their","if","will",
"up","other","about","out","many","then","them","these","so",
"some","her","would","make","like","him","into","time","has",
"look","two","more","write","go","see","number","no","way",
"could","people","my","than","first","water","been","call",
"who","oil","its","now","find","long","down","day","did","get",
"come","made","may","part"
];
// declared variables
var randomNumber = Math.floor(Math.random() * 100);
var randomWord = hangmanWords[randomNumber];
var underscoreCount = randomWord.length;
var underscoreArr = [];
var counter = randomWord.length +3;
var numberTest = 0;
var lettersGuessedArr = [];
var lettersGuessedClass = document.querySelector('.letters-guessed');
var li = document.getElementsByClassName('tester');
var textValue = document.querySelector('.text-value');
var attemptTitle = document.querySelector('.attempt-title');
var hangmanWordClass = document.querySelector('.hangman-word');
var hangmanLettersClass = document.querySelector('.hangman-letters');
// actions
attemptTitle.innerHTML = "You have this many attempts left: " + counter;
console.log(randomWord);
function setGuess(guess) {
personGuess = guess;
}
for (i=0;i<underscoreCount;i+=1) {
underscoreArr.push("_ ");
underscoreArr.join(" ");
var underscoreArrString = underscoreArr.toString();
var underscoreArrEdited = underscoreArrString.replace(/,/g," ");
hangmanLettersClass.innerHTML = underscoreArrEdited;
}
function pushGuess () {
lettersGuessedArr.push(personGuess);
var lettersGuessedArrString = lettersGuessedArr.toString();
var lettersGuessedArrEdited = lettersGuessedArrString.replace(/,/g," ");
lettersGuessedClass.innerHTML = lettersGuessedArrEdited;
}
function checkGuess() {
for (var i=0;i<randomWord.length;i+=1) {
if (personGuess === randomWord[i]) {
console.log(personGuess);
numberTest = i;
li[i].textContent = randomWord[i];
i += 20;
textValue.value= "";
} else if ((randomWord.length - 1) > i ) {
console.log("works");
} else {
pushGuess();
counter -= 1;
attemptTitle.innerHTML = "You have made this many attempts: " + counter;
textValue.value= "";
}
}
};
My bin:
http://jsbin.com/dawewiyipe/4/edit
You had a stray bit of code that didn't belong:
i += 20;
I took it out, and the problem went away (the loop was intended to check each character, the +=20 broke the process of checking each character)
function checkGuess() {
for (var i=0;i<randomWord.length;i+=1) {
if (personGuess === randomWord[i]) {
console.log(personGuess);
numberTest = i;
li[i].textContent = randomWord[i];
textValue.value= "";
} else if ((randomWord.length - 1) > i ) {
console.log("works");
} else {
pushGuess();
counter -= 1;
attemptTitle.innerHTML = "You have made this many attempts: " + counter;
textValue.value= "";
}
}
}
http://jsbin.com/noxiqefaji/1/edit

how to change the value of input box just for display in html 5 web page

I have a textfield in which i am entering data i want that if user enter 1000 then it show 1,000 in textfield but this same value 1000 is also used in calculations further so how to solve this if user enter 1000 then just for display it show 1,000 and if we use in calcualtion then same var shows 1000 for calculating.
<HTML>
<body>
<input type="text" id="test" value="" />
</body>
<script>
var c=document.getElementById(test);
</script>
</html>
so if c user enter 1000 then it should dispaly 1,000 for dispaly one and if user uses in script
var test=c
then test should show 1000
document.getElementById returns either null or a reference to the unique element, in this case a input element. Input elements have an attribute value which contains their current value (as a string).
So you can use
var test = parseInt(c.value, 10);
to get the current value. This means that if you didn't use any predefined value test will be NaN.
However, this will be evaluated only once. In order to change the value you'll need to add an event listener, which handles changes to the input:
// or c.onkeyup
c.onchange = function(e){
/* ... */
}
Continuing form where Zeta left:
var testValue = parseInt(c.value);
Now let's compose the display as you want it: 1,000
var textDecimal = c.value.substr(c.value.length-3); // last 3 characters returned
var textInteger = c.value.substr(0,c.value.length-3); // characters you want to appear to the right of the coma
var textFinalDisplay = textInteger + ',' + textDecimal
alert(textFinalDisplay);
Now you have the display saved in textFinalDisplay as a string, and the actual value saved as an integer in c.value
<input type="text" id="test" value=""></input>
<button type="button" id="get">Get value</input>
var test = document.getElementById("test"),
button = document.getElementById("get");
function doCommas(evt) {
var n = evt.target.value.replace(/,/g, "");
d = n.indexOf('.'),
e = '',
r = /(\d+)(\d{3})/;
if (d !== -1) {
e = '.' + n.substring(d + 1, n.length);
n = n.substring(0, d);
}
while (r.test(n)) {
n = n.replace(r, '$1' + ',' + '$2');
}
evt.target.value = n + e;
}
function getValue() {
alert("value: " + test.value.replace(/,/g, ""));
}
test.addEventListener("keyup", doCommas, false);
button.addEventListener("click", getValue, false);
on jsfiddle
you can get the actual value from variable x
<html>
<head>
<script type="text/javascript">
function abc(){
var x = document.getElementById('txt').value;
var y = x/1000;
var z = y+","+ x.toString().substring(1);
document.getElementById('txt').value = z;
}
</script>
</head>
<body>
<input type="text" id="txt" value="" onchange = "abc()"/>
</body>
This works with integer numbers on Firefox (Linux). You can access the "non-commaed"-value using the function "intNumValue()":
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
String.prototype.displayIntNum = function()
{
var digits = String(Number(this.intNumValue())).split(""); // strip leading zeros
var displayNum = new Array();
for(var i=0; i<digits.length; i++) {
if(i && !(i%3)) {
displayNum.unshift(",");
}
displayNum.unshift(digits[digits.length-1-i]);
}
return displayNum.join("");
}
String.prototype.intNumValue = function() {
return this.replace(/,/g,"");
}
function inputChanged() {
var e = document.getElementById("numInp");
if(!e.value.intNumValue().replace(/[0-9]/g,"").length) {
e.value = e.value.displayIntNum();
}
return false;
}
function displayValue() {
alert(document.getElementById("numInp").value.intNumValue());
}
</script>
</head>
<body>
<button onclick="displayValue()">Display value</button>
<p>Input integer value:<input id="numInp" type="text" oninput="inputChanged()">
</body>
</html>

Count textarea characters

I am developing a character count for my textarea on this website. Right now, it says NaN because it seems to not find the length of how many characters are in the field, which at the beginning is 0, so the number should be 500. In the console in chrome developer tools, no error occur. All of my code is on the site, I even tried to use jQuery an regular JavaScript for the character count for the textarea field, but nothing seems to work.
Please tell me what I am doing wrong in both the jQuery and the JavaScript code I have in my contact.js file.
$(document).ready(function() {
var tel1 = document.forms["form"].elements.tel1;
var tel2 = document.forms["form"].elements.tel2;
var textarea = document.forms["form"].elements.textarea;
var clock = document.getElementById("clock");
var count = document.getElementById("count");
tel1.addEventListener("keyup", function (e){
checkTel(tel1.value, tel2);
});
tel2.addEventListener("keyup", function (e){
checkTel(tel2.value, tel3);
});
/*$("#textarea").keyup(function(){
var length = textarea.length;
console.log(length);
var charactersLeft = 500 - length;
console.log(charactersLeft);
count.innerHTML = "Characters left: " + charactersLeft;
console.log("Characters left: " + charactersLeft);
});​*/
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
});
function checkTel(input, nextField) {
if (input.length == 3) {
nextField.focus();
} else if (input.length > 0) {
clock.style.display = "block";
}
}
function textareaLengthCheck(textarea) {
var length = textarea.length;
var charactersLeft = 500 - length;
count.innerHTML = "Characters left: " + charactersLeft;
}
$("#textarea").keyup(function(){
$("#count").text($(this).val().length);
});
The above will do what you want. If you want to do a count down then change it to this:
$("#textarea").keyup(function(){
$("#count").text("Characters left: " + (500 - $(this).val().length));
});
Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks #Niet)
document.getElementById('textarea').onkeyup = function () {
document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};
⚠️ The accepted solution is outdated.
Here are two scenarios where the keyup event will not get fired:
The user drags text into the textarea.
The user copy-paste text in the textarea with a right click (contextual menu).
Use the HTML5 input event instead for a more robust solution:
<textarea maxlength='140'></textarea>
JavaScript (demo):
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", event => {
const target = event.currentTarget;
const maxLength = target.getAttribute("maxlength");
const currentLength = target.value.length;
if (currentLength >= maxLength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(`${maxLength - currentLength} chars left`);
});
And if you absolutely want to use jQuery:
$('textarea').on("input", function(){
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if( currentLength >= maxlength ){
console.log("You have reached the maximum number of characters.");
}else{
console.log(maxlength - currentLength + " chars left");
}
});
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
You are calling textareaLengthCheck and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:
textarea.addEventListener("keypress",textareaLengthCheck,false);
Aside from that:
var length = textarea.length;
textarea is the actual textarea, not the value. Try this instead:
var length = textarea.value.length;
Combined with the previous suggestion, your function should be:
function textareaLengthCheck() {
var length = this.value.length;
// rest of code
};
Here is simple code. Hope it help you
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>
This code gets the maximum value from the maxlength attribute of the textarea and decreases the value as the user types.
<DEMO>
var el_t = document.getElementById('textarea');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length - this.value.length);
};
<textarea id="textarea" name="text"
maxlength="500"></textarea>
<span id="count"></span>
I found that the accepted answer didn't exactly work with textareas for reasons noted in Chrome counts characters wrong in textarea with maxlength attribute because of newline and carriage return characters, which is important if you need to know how much space would be taken up when storing the information in a database. Also, the use of keyup is depreciated because of drag-and-drop and pasting text from the clipboard, which is why I used the input and propertychange events. The following takes newline characters into account and accurately calculates the length of a textarea.
$(function() {
$("#myTextArea").on("input propertychange", function(event) {
var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;
$("#counter").html(curlen);
});
});
$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="myTextArea"></textarea><br>
Size: <span id="counter" />
For those wanting a simple solution without jQuery, here's a way.
textarea and message container to put in your form:
<textarea onKeyUp="count_it()" id="text" name="text"></textarea>
Length <span id="counter"></span>
JavaScript:
<script>
function count_it() {
document.getElementById('counter').innerHTML = document.getElementById('text').value.length;
}
count_it();
</script>
The script counts the characters initially and then for every keystroke and puts the number in the counter span.
Martin
They say IE has issues with the input event but other than that, the solution is rather straightforward.
ta = document.querySelector("textarea");
count = document.querySelector("label");
ta.addEventListener("input", function (e) {
count.innerHTML = this.value.length;
});
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">
</textarea>
<label for="my-textarea"></label>
var maxchar = 10;
$('#message').after('<span id="count" class="counter"></span>');
$('#count').html(maxchar+' of '+maxchar);
$('#message').attr('maxlength', maxchar);
$('#message').parent().addClass('wrap-text');
$('#message').on("keydown", function(e){
var len = $('#message').val().length;
if (len >= maxchar && e.keyCode != 8)
e.preventDefault();
else if(len <= maxchar && e.keyCode == 8){
if(len <= maxchar && len != 0)
$('#count').html(maxchar+' of '+(maxchar - len +1));
else if(len == 0)
$('#count').html(maxchar+' of '+(maxchar - len));
}else
$('#count').html(maxchar+' of '+(maxchar - len-1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="message" name="text"></textarea>
$(document).ready(function(){
$('#characterLeft').text('140 characters left');
$('#message').keydown(function () {
var max = 140;
var len = $(this).val().length;
if (len >= max) {
$('#characterLeft').text('You have reached the limit');
$('#characterLeft').addClass('red');
$('#btnSubmit').addClass('disabled');
}
else {
var ch = max - len;
$('#characterLeft').text(ch + ' characters left');
$('#btnSubmit').removeClass('disabled');
$('#characterLeft').removeClass('red');
}
});
});
This solution will respond to keyboard and mouse events, and apply to initial text.
$(document).ready(function () {
$('textarea').bind('input propertychange', function () {
atualizaTextoContador($(this));
});
$('textarea').each(function () {
atualizaTextoContador($(this));
});
});
function atualizaTextoContador(textarea) {
var spanContador = textarea.next('span.contador');
var maxlength = textarea.attr('maxlength');
if (!spanContador || !maxlength)
return;
var numCaracteres = textarea.val().length;
spanContador.html(numCaracteres + ' / ' + maxlength);
}
span.contador {
display: block;
margin-top: -20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="100" rows="4">initial text</textarea>
<span class="contador"></span>

Using Regex to limit special characters in a textbox using jquery in ASP.net MVC form

I'm trying to limit to 3 the number of special characters in a text box using JQuery. The special characters can be in any order and can be adjacent to each other or scattered over the length of the text box. I spent the last 24 hours reading almost all relevant posts in stackoverflow and trying the suggestions.
I still haven't come with a suitable regex.
Here is what I have so far at the bottom of my ASP.net mvc form:
<script type="text/javascript">
$(document).ready(function () {
$('input[id$=textbox1]').bind('blur', function () {
var match = /^[.,:;!?€¥£¢$-~#%&*()_]{4,50}$/g.test(this.value);
if (match == true)
alert("Please enter a maximum of 3 special characters.");
});
});
</script>
Below is the list of special characters I'm targeting:
~`!##%^&*()-_:;?€¥£¢$-~{}[]<>/+|=
You where thinking to difficullty. Just count how often the elements are inside the input and throw a warning when the count is over three.
here is an
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="jquery-1.8.3.min.js"></script>
<script>
var limitchars = '[~`!##%\^&\*\(\)-_:;\?€¥£¢\${}\[]<>/+\|=]'
$(function () {
var teststring = "~`!##%\^&\*\(\)-_:;\?€¥£¢\${}\[]<>/+\|='-:;";
var regex = /[~`'!##%\^&\*\(\)-_:;\?€¥£¢\${}\[\]<>/+\|=]/g
//var test1 = teststring.match(regex);
//debugger;
//alert(teststring.length === test1.length);
$('input').keyup(function () {
var text = this.value;
var match = text.match(regex);
if (match.length > 3) {
alert('invalidI input');
}
});
});
</script>
</head>
<body>
<input type="text" />
</body>
</html>
Don't forget to escape the regular expression (http://www.regular-expressions.info/reference.html ). The g at the end of the regex counts the number of occurrence in string (http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string )
You can find the number of bad characters by counting the number of matches.
Working example at http://jsbin.com/alidus/1/
$(document).ready(function () {
$('#test').bind('blur', function () {
var charactersToExlude = "~`!##%^&*()-_:;?€¥£¢$-~{}[]<>/+|=";
var badCharacterRegex = "[" + charactersToExlude.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") + "]";
console.log(badCharacterRegex);
var patt=new RegExp(badCharacterRegex, "g");
var matches = this.value.match(patt);
var numberOfBadCharacters = matches ? matches.length : 0;
if (numberOfBadCharacters >= 3) {
$("#result").text("Please enter a maximum of 3 special characters. (" + numberOfBadCharacters + " bad characters).");
} else {
$("#result").text(numberOfBadCharacters + " bad characters.");
}
});
});
First we escape any bad characters that have meaning to regex. Then crete the pattern, match it, if any matches, count the number of matches.
$(document).ready(function () {
$('#test').bind('blur', function () {
var charactersToExlude = "~`!##%^&*()-_:;?€¥£¢$-~{}[]<>/+|=";
var badCharacterRegex = "[" + charactersToExlude.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") + "]";
console.log(badCharacterRegex);
var patt=new RegExp(badCharacterRegex, "g");
var matches = this.value.match(patt);
var numberOfBadCharacters = matches ? matches.length : 0;
if (numberOfBadCharacters >= 3) {
$("#result").text("Please enter a maximum of 3 special characters. (" + numberOfBadCharacters + " bad characters).");
} else {
$("#result").text(numberOfBadCharacters + " bad characters.");
}
});
});

Categories

Resources