Max-Length for multiple text areas using php and Javascript - javascript

I am trying to display the number of characters left in multiple text areas. Although I have different ID's for the text areas, the max length is prompted only for the 2nd text area and not for the first. My code is as shown below
<textarea id="txtBox"></textarea>
<input type="text" id="counterBox"/>
<script>
var txtBoxRef = document.querySelector("#txtBox");
var counterRef = document.querySelector("#counterBox");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef.value.length);
if(remLength < 0)
{
txtBoxRef.value = txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value = remLength + " characters remaining...";
},true);
</script>
<textarea id="txtBox1"></textarea>
<input type="text" id="counterBox1"/>
<script>
var txtBoxRef = document.querySelector("#txtBox1");
var counterRef = document.querySelector("#counterBox1");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef.value.length);
if(remLength < 0)
{
txtBoxRef.value = txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value = remLength + " characters remaining...";
},true);
</script>
The result is as below (What I have):
What I want :

Looks like the variables txtBoxRef and counterRef are in the same scope area, you declared twice.
<textarea id="txtBox"></textarea>
<input type="text" id="counterBox"/>
<script>
var txtBoxRef = document.querySelector("#txtBox");
var counterRef = document.querySelector("#counterBox");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef.value.length);
if(remLength < 0)
{
txtBoxRef.value = txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value = remLength + " characters remaining...";
},true);
</script>
<textarea id="txtBox1"></textarea>
<input type="text" id="counterBox1"/>
<script>
var txtBoxRef1 = document.querySelector("#txtBox1");
var counterRef1 = document.querySelector("#counterBox1");
txtBoxRef1.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef1.value.length);
if(remLength < 0)
{
txtBoxRef1.value = txtBoxRef1.value.substring(0, 160);
return false;
}
counterRef1.value = remLength + " characters remaining...";
},true);
</script>
check Fiddle

Try this:
<textarea id="txtBox"></textarea>
<input type="text" id="counterBox"/>
<script>
var txtBoxRef=document.querySelector("#txtBox");
var counterRef=document.querySelector("#counterBox");
txtBoxRef.addEventListener("keyup", function(){
var remLength=0;
remLength=160 - parseInt(txtBoxRef.value.length);
if(remLength < 0){
txtBoxRef.value=txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value=remLength + " characters remaining...";
}, true);
</script>
<textarea id="txtBox1"></textarea>
<input type="text" id="counterBox1"/>
<script>
var txtBoxRef1=document.querySelector("#txtBox1");
var counterRef1=document.querySelector("#counterBox1");
txtBoxRef1.addEventListener("keyup", function(){
var remLength=0;
remLength=160 - parseInt(txtBoxRef1.value.length);
if(remLength < 0){
txtBoxRef1.value=txtBoxRef1.value.substring(0, 160);
return false;
}
counterRef1.value=remLength + " characters remaining...";
}, true);
</script>
Your code can be optimized if you give it a thought.

Related

Is there a way to split inserted value for example 1234567890 to 12345 and 67890?

Is there a function that splits the the given string into 2 evenly and place half of each to different textboxes?
I have tried var.split and var.slice
<script>
function display()
{
var myStr = document.getElementbyId("reqnum").value;
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
}
the expected should split the no. evenly and would display an error if the numbers are odd.
You can check the length of your input string. If it is odd then display an error.
<input type="text" id="reqnum" >
<input type="button" value="Display" onclick="display()">
<script>
function display()
{
var myStr = document.getElementById("reqnum").value;
if( !myStr || myStr.length % 2 == 1){
document.write("<p>Invalid input</p>");
}else{
var a = parseInt(myStr.substring(0, myStr.length/2));
var b = parseInt(myStr.substring(myStr.length/2, myStr.length));
document.write("<p>" + a + "</p>");
document.write("<p>" + b + "</p>");
document.write("<p> Result after multiplication : " + (a*b) + "</p>");
}
}
</script>
you can convert the numbers to string and then you can do the following.
var num = "1234567890"
var num1
var num2
if (num.length % 2 == 0) {
num1 = num.slice(0, (num.length / 2))
num2 = num.slice((num.length / 2))
} else {
console.log("Number contains odd number of digits")
}
console.log("Num1 " + num1 + " and Num2 " + num2)
use the Slice method, documentation is here.
For your slicing in half:
let half1, half2;
if( myStr.length % 2 == 0 ){
half1 = myStr.slice(0, (myStr.length / 2));
half2 = myStr.slice( (myStr.length / 2), myStr.length );
} else {
// error code
}
function splitToEqual(num){
num = num.toString()
return [num.substring(0, num.length / 2), num.substring(num.length / 2, num.length)]
}
console.log(splitToEqual(1234567890))
Have you tried using slice and length String methods?
Ie.
const string = '1234567890';
const length = string.length;
const res1 = string.slice(0,length/2);
const res2 = string.slice(length/2);
console.log(res1,res2);
Based on your request, I created the following piece of code :-)
Hope it helps.
var inputBox, warning, fBox, sBox;
function inputBoxChanged(e) {
var text = e.currentTarget.value;
if (text.length % 2 != 0) {
warning.innerText = "Value needs to be even sized";
fBox.value = "";
sBox.value = "";
} else {
warning.innerText = "";
var splitPos = text.length / 2;
fBox.value = text.slice(0, splitPos);
sBox.value = text.slice(splitPos, text.length);
}
}
document.addEventListener("DOMContentLoaded", function (e) {
inputBox = document.getElementById("input");
warning = document.getElementById("warning");
fBox = document.getElementById("first");
sBox = document.getElementById("second");
inputBox.addEventListener("change", inputBoxChanged);
});
<html>
<body>
<input id="input" type="text"/>
<span id="warning"></span>
<hr/>
<input id="first" type="text" readonly/>
<input id="second" type="text"readonly/>
</body>
</html>
Use substring() function as
var substring=string.substring(strating_index,end_index);
index will start from 0
var str="1234567890"
var substr=str.substring(0,str.length/2);
var substr2=str.substring(strlength/2,strlength);
$("#ID1").val(substr);
$('#ID2').val(substr2);

buttons don't work after append - jquery

buttons won't work after appended elements take up same Y position, why is this happening? I took the advice of other posts and made my onclick functions a certain way but I am still having issues
js:
var welldataArray = [];
var productiondataArray = [];
var radioSearchPartB = 0;
var productionjsonarray = [];
$(document).ready(function() {
$(document).on('click', '.clearButton', function (){
$('#result1').empty();
$('#block1').val("");
$('#block2').val("");
$('#block3').val("");
$('#block4').val("");
$('#block5').val("");
});
$(document).on('click', '.searchButton', function(){
//validate
if(radioSearchPartB == 1){
var block1 = $("#block1").val().toUpperCase();
var firstcharBlock1 = block1.substring(0,1);
var secondcharBlock1 = block1.substring(1,3);
var secondParsed = parseInt(secondcharBlock1);
var block2 = $("#block2").val();
var block3 = $("#block3").val();
var block4 = $("#block4").val().toUpperCase();
var firstcharBlock4 = block4.substring(0,1);
var secondcharBlock4 = block4.substring(1,3);
var msg = "";
if(firstcharBlock1!= 'A' && firstcharBlock1!= 'B' && firstcharBlock1!= 'C' && firstcharBlock1!= 'D'){
msg+="First text box Invalid Format: First character Range A-D\n";
}
if(secondParsed < 1 || secondParsed > 16 || isNaN(secondParsed) || !($.isNumeric(secondcharBlock1))){
msg+="First text box Invalid Format: Second Character Range 1-16\n";
}
if(parseInt(block2) < 1 || parseInt(block2) > 126 || block2.length == 0 || isNaN(parseInt(block2)) ){
msg+="Second text box Invalid Format: Must be a number 1-126\n"
}
if(isNaN(parseInt(block3)) || parseInt(block3) < 1 || parseInt(block3) > 24 || block3.length == 0){
msg+="Third text box Invalid Format: Must be a number 1-24\n";
}
if(firstcharBlock4 != 'W' || parseInt(secondcharBlock4) < 4 || parseInt(secondcharBlock4) > 6){
msg+= "Fourth text box Invalid Format: W and then a number 4-6\n";
}
if(msg.length > 0){
alert(msg);
return;
}
//then
$('#result1').empty();
var i = 0;
productionjsonarray = [];
while(i < productiondataArray.length){
var jsonObject = {
"location": productiondataArray[i++].trim(),
"date": productiondataArray[i++].trim(),
"oilproduction": productiondataArray[i++].trim(),
"waterproduction": productiondataArray[i++].trim(),
"gasproduction": productiondataArray[i++].trim()
}
productionjsonarray.push(jsonObject);
}
var assemble = block1 + "-" + block2 + "-" + block3 + "-" + block4;
var check = false;
for(var i = 0; i < welldataArray.length; i++){
if(welldataArray[i].trim() == assemble){
for(var j = 0; j < productionjsonarray.length; j++){
if(productionjsonarray[j].location.trim() == welldataArray[i].trim()){
$('#result1').append(productionjsonarray[j].location.trim() + " "
+ productionjsonarray[j].date.trim() + " " + productionjsonarray[j].oilproduction.trim()
+ " " + productionjsonarray[j].waterproduction.trim() + " " + productionjsonarray[j].gasproduction.trim() + "<br>");
check = true;
}
}
}
}
if(check == false){
alert("No match to search");
return;
}
} else {
//validate
var block5 = $("#block5").val().toUpperCase();
var firstcharBlock5 = block5.substring(0,1);
var secondcharBlock5 = block5.substring(1,3);
var secondParsed5 = parseInt(secondcharBlock5);
var msg = "";
if(firstcharBlock5!= 'A' && firstcharBlock5!= 'B' && firstcharBlock5!= 'C' && firstcharBlock5!= 'D'){
msg+="text box Invalid Format: First character Range A-D\n";
}
if(secondParsed5 < 1 || secondParsed5 > 16 || isNaN(secondParsed5) || !($.isNumeric(secondcharBlock5))){
msg+="text box Invalid Format: Second Character Range 1-16\n";
}
if(msg.length > 0){
alert(msg);
return;
}
//then
var check = false;
$('#result1').empty();
for(var i = 0; i < welldataArray.length; i++){
if(welldataArray[i].trim().indexOf(block5.trim()) >= 0){
$('#result1').append(welldataArray[i] + " " + welldataArray[i+1] + " " + welldataArray[i+2] + " " + welldataArray[i+3] + " " + welldataArray[i+4] + " " + welldataArray[i+5] + "<br>");
check = true;
}
}
if(check == false){
alert("No match to search");
return;
}
var i = 0;
productionjsonarray = [];
while(i < productiondataArray.length){
var jsonObject = {
"location": productiondataArray[i++].trim(),
"date": productiondataArray[i++].trim(),
"oilproduction": productiondataArray[i++].trim(),
"waterproduction": productiondataArray[i++].trim(),
"gasproduction": productiondataArray[i++].trim()
}
productionjsonarray.push(jsonObject);
}
}
});
$.ajax({
type: "GET",
url: "welldata.xml",
dataType: "xml",
success: function(xml){
$(xml).find('welldata').each(function(){ //code provided by stack overflow: http://stackoverflow.com/questions/6542187/xml-to-javascript-array-with-jquery
var location;
var welldepth;
var perfdepth;
var perfzone;
var stroke;
var strokepermin;
location = $('location', this).text();
welldepth = $('welldepth', this).text();
perfdepth = $('perfdepth', this).text();
perfzone = $('perfzone', this).text();
stroke = $('stroke', this).text();
strokepermin = $('strokepermin', this).text();
welldataArray.push(location);
welldataArray.push(welldepth);
welldataArray.push(perfdepth);
welldataArray.push(perfzone);
welldataArray.push(stroke);
welldataArray.push(strokepermin);
});
}
});
$.ajax({
type: "GET",
url: "productiondata.xml",
dataType: "xml",
success: function(xml){
$(xml).find('productiondata').each(function(){
var location;
var date;
var oilproduction;
var waterproduction;
var gasproduction;
location = $('location', this).text();
date = $('date', this).text();
oilproduction = $('oilproduction', this).text();
waterproduction = $('waterproduction', this).text();
gasproduction = $('gasproduction', this).text();
productiondataArray.push(location);
productiondataArray.push(date);
productiondataArray.push(oilproduction);
productiondataArray.push(waterproduction);
productiondataArray.push(gasproduction);
});
$( "#searchButton" ).click(function() {
radioSearchPartB = $('input[name=searchChoice]:checked').val()
});
}
});
});
function loadPartB(){
document.getElementById("block1").maxLength = "3";
document.getElementById("block2").maxLength = "3";
document.getElementById("block3").maxLength = "2";
document.getElementById("block4").maxLength = "2";
document.getElementById("block5").maxLength = "3";
radioSearchPartB = $('input[name=searchChoice]:checked').val();
$('#result1').html('');
$('#result1').empty();
if(radioSearchPartB == 2){
$("#1stblocks").hide();
$("#1stex").hide();
$("#2ndblocks").show();
$("#2ndex").show();
} else {
$("#1stblocks").show();
$("#1stex").show();
$("#2ndblocks").hide();
$("#2ndex").hide();
}
}
html:
<!DOCTYPE html>
<html class="colorful">
<head>
<meta charset="utf-8">
<title>Final Project</title>
<link rel="stylesheet" type="text/css" href="css/final.css">
<script src="jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="final.js"></script>
</head>
<body onload="loadPartB()">
Cameron Steinburg 734972
<br>
<h1>This is Part B</h1>
<br>
<h2>Oil Well Database</h2>
<div id="result1"></div>
<br>
<input type="radio" name="searchChoice" value="1" checked onchange="loadPartB()"> Search by specific location
<input type="radio" name="searchChoice" value="2" onchange="loadPartB()"> Search by section
<br>
<br>
<table id="1stblocks">
<tr>
<td><input type="text" id="block1">-</td>
<td><input type="text" id="block2">-</td>
<td><input type="text" id="block3">-</td>
<td><input type="text" id="block4"></td>
<td></td>
</tr>
</table>
<div id="1stex">
ex. B15-98-17-W5
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<table id="2ndblocks">
<tr>
<td><input type="text" id="block5"></td>
</tr>
</table>
<div id="2ndex">
ex. B15
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<div>
<input type="submit" value="Search" class="searchButton">
<input type="submit" value="Clear" class="clearButton">
</div>
<br>
<br>
<h3>Main Page Part C Part D</h3>
</body>
</html>
Well, your buttons works if you remove onload="loadPartB()" from body and call the loadPartB(); in your document.ready()
$(document).ready(function() {
loadPartB();
$(document).on('click', '.clearButton', function (){
$('#result1').empty();
$('#block1').val("");
$('#block2').val("");
$('#block3').val("");
$('#block4').val("");
$('#block5').val("");
});
you can use delegate() as :
$(document).delegate('click', '.clearButton', function (){
// your code
});
document : http://api.jquery.com/delegate/
this event alway set to new elements

User inputs information into text box which makes allows user to select multiple words and creates different Titles based on the selections

I am gaining user input from four different areas and I want to take those options and convert them to an array which will loop through and display different variations of the words selected. The problem I am having is that the array will not cycle through the variables when passed through it unless they are already pre-defined.
<!DOCTYPE html>
<html>
<head>
<title> Title Generation Module</title>
<script src="title.js" type="text/javascript"></script>
<script src="find.js" type="text/javascript"></script>
<script src="replace.js" type="text/javascript"></script>
<script src="search.js" type="text/javascript"></script>
<script src="generate.js" type="text/javascript"></script>
<!-- <script src="check.js" type="text/javascript"></script>--> <!-- Leaving for future usage not needed at this point -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="jquery-1.11.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="title.css">
</head>
<body>
<h1>Title Generation Module</h1>
<h2>Example</h2>
<p>When you type into Core Words you want to put words that cannot change such as: Logitech
</br> For Word Combinations you want to use words such as: Brand New or Power Adaptor
</br> For Swapped Words you might want to use: Gaming instead of Performance or vice versa
</br> For Synonyms you want to use words that mean the same thing such as for = 4 or at = #</p>
<h3>Core Words</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newCore"/>
<button id="addCore">Insert</button>
<label for="coreContain">Select as many as you like:</label>
<select id="coreContain" name="coreContain" multiple></select>
<button id="checkCore" onclick="checkCore()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addCore").click(function()
{
$("#coreContain").append('<option value="' + $("#newCore").val() + '">' + $("#newCore").val() + '</option>');
});
});
$('#coreContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var coreOptions = new Array();
$('form').submit(
function()
{
$('#coreContain > option:selected').each(
function(i)
{
coreOptions[i] = $(this).val();
});
//window.alert(coreOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs Word Combinations -->
<h3>Word Combinations</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newCombo"/>
<button id="addCombo">Insert</button>
<label for="comboContain">Select as many as you like:</label>
<select id="comboContain" name="comboContain" multiple></select>
<button id="checkCombo" onclick="checkWordCombo()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addCombo").click(function()
{
$("#comboContain").append('<option value="' + $("#newCombo").val() + '">' + $("#newCombo").val() + '</option>');
});
});
$('#comboContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var comboOptions = new Array();
$('form').submit(
function()
{
$('#comboContain > option:selected').each(
function(i)
{
comboOptions[i] = $(this).val();
});
//window.alert(comboOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs words that can swap -->
<h3>Words that can be Swapped</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newSwap"/>
<button id="addSwap">Insert</button>
<label for="swapContain">Select as many as you like:</label>
<select id="swapContain" name="comboSwap" multiple></select>
<button id="checkSwap" onclick="checkSwap()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addSwap").click(function()
{
$("#swapContain").append('<option value="' + $("#newSwap").val() + '">' + $("#newSwap").val() + '</option>');
});
});
$('#swapContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var swapOptions = new Array();
$('form').submit(
function()
{
$('#swapContain > option:selected').each(
function(i)
{
swapOptions[i] = $(this).val();
});
//window.alert(swapOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs words that can be use as Synonyms -->
<h3>Words that can be used as Synonyms</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newSyn"/>
<button id="addSyn">Insert</button>
<label for="synContain">Select as many as you like:</label>
<select id="synContain" name="comboSyn" multiple></select>
<button id="checkSyn" onclick="checkSyn()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addSyn").click(function()
{
$("#synContain").append('<option value="' + $("#newSyn").val() + '">' + $("#newSyn").val() + '</option>');
});
});
$('#synContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var synOptions = new Array();
$('form').submit(
function()
{
$('#synContain > option:selected').each(
function(i)
{
synOptions[i] = $(this).val();
});
//window.alert(synOptions);
return false;
});
</script>
</fieldset>
</form>
<button onclick="generate_title()">Generate Titles</button>
<button onclick="displayList()">Click Me</button>
<script>
function displayList()
{
alert(coreOptions+ " " +comboOptions +" " +swapOptions+ " " +synOptions);
}
</script>
<div id="display"></div>
</body>
</html>
External Javascript
var check = ["Facebook", "MySpace", "Twitter"];
//document.getElementById("coreOptions");
//var checkX = check.splice(" ");
var checkY = document.getElementById("swapOptions");
var input_keywords =
[
[check, check],
//[checkY,checkY],
["Cordless-","Wireless"],
["Rechargeable+"],
].filter(function(item){
return item.length <= 80;
});
/*[
["Men", "Women", "Unisex"],
["1", "2", "3", "fourrrrrrrrrr"],
["Candy Color"],
["Spring"],
["Ski+"],
["Crochet"],
["Hip-hop"],
["Hat Beanie-"],
["One Size+"]].filter(function(item)
{
return item.length <= 80;
});
*/
/*
var input_keywords = [
["Women Men", "Men Women", "Unisex Women Men", "Unisex Men Women", "Unisex", "Womens Mens", "Mens Womens", "Unisex Womens Mens", "Unisex Mens Womens"],
["Fashion", "Trendy", "Stylish", "Korea Style"],
["Candy Color"],
["Spring", "Summer", "Winter"],
["Ski"],
["Crochet", "Knit", "Knitted"],
["Elastic", "Strechable"],
["Hip-hop", "Dance"],
["Hat", "Cap", "Beanie", "Hat Cap", "Hat Beanie", "Hat Cap Beanie"],
["One Size"]
].filter(function(item){
return item.length <= 80;
});
*/
var limit_count = 24;
var max_char_per_title = 80;
var sub_library = ["for=4", "you=u", "at=#", "two=2", "with=w", "adapter=adpt", "Monokini=Mono 9"].map( function (item)
{ return item.split("=");});
function calc_length(title)
{
return (title
.join(" ") + " ")
.replace("- ", " ")
.replace("+ ", " ")
.replace("* ", " ")
.replace(" ", " ")
.replace("\" ", " ")
.replace(" \"", " ")
.length - 1;
}
function get_all_titles(keywords)
{
var result_titles = [];
for(var i = 0; i < keywords.length; i ++)
{
var word_count = keywords[i].length;
var words = keywords[i];
var previous_count = result_titles.length;
if (previous_count == 0)
{
previous_count = word_count;
for (var sub_ii = 0 ; sub_ii < word_count; sub_ii++)
{
result_titles[sub_ii] = [];
result_titles[sub_ii][i] = words[sub_ii];
}
}
else
{
for (var sub_i = 0; sub_i < word_count; sub_i++)
{
for (var sub_ii = 0 ; sub_ii < previous_count; sub_ii++)
{
if (result_titles[previous_count * sub_i + sub_ii] == undefined)
{
result_titles[previous_count * sub_i + sub_ii] = result_titles[sub_ii ].slice();
}
result_titles[previous_count * sub_i + sub_ii][i] = words[sub_i];
}
}
}
}
return result_titles;
}
function substitute(title)
{
for (var subs_idx = 0 ; subs_idx < sub_library.length; subs_idx++)
{
var index = title.indexOf(sub_library[subs_idx][0]);
if (index >= 0)
{
title[index] = sub_library[subs_idx][1];
}
}
return title;
}
function shorten_title_length(titles)
{
var result = [];
var count = 0;
for (var i = 0 ; i < titles.length; i++)
{
if (calc_length(titles[i]) > max_char_per_title)
{
//substitute with the word in library
titles[i] = substitute(titles[i]);
// still too long, remove possible words.
if (calc_length(titles[i]) > max_char_per_title)
{
var words = titles[i];
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx].indexOf("/") == (words[word_idx].length - 1))
{
titles[i] = titles[i].splice(word_idx, 1);
}
}
titles[i] = words
}
}
if (calc_length(titles[i]) <= max_char_per_title)
{
result[count] = titles[i];
count++;
}
else
{
console.log(titles[i].join(" \ "));
}
}
return result;
}
function change_forward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "-")
{
if (word_idx != words.length - 1)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx + 1];
words[word_idx + 1] = tmp;
word_idx ++;
}
}
}
title = words;
return title;
}
function change_backward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "+")
{
if (word_idx != 0)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx - 1];
words[word_idx - 1] = tmp;
}
}
}
title = words;
return title;
}
function finalize(titles)
{
for (var title_idx = 0 ; title_idx < titles.length; title_idx++)
{
for (var word_idx = 0 ; word_idx < titles[title_idx].length; word_idx++)
{
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '+')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '-')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '/')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '"')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '*')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
}
}
return titles;
}
function generate_title()
{
var all_titles = get_all_titles(input_keywords);
//Check keyword files provided by the user, that optional sub words are at least 24
if (all_titles.length < limit_count)
{
alert("not enough different titles");
}
//check total char per title
all_titles = shorten_title_length(all_titles);
// substitute half randomly.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = substitute(all_titles[i]);
}
}
//changing position backward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_backward_position(all_titles[i]);
}
}
//changing position forward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_forward_position(all_titles[i]);
}
}
all_titles = finalize(all_titles);
// evaluate.....
for (var i = 0 ; i < all_titles.length; i++)
{
console.log(i);
console.log(all_titles[i].join(" \ "));
console.log(all_titles[i].length);
alert(all_titles);
}
}

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>

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources