Count and display number of characters in a textbox using Javascript - javascript

I am working on a project that requires me to count the number of characters entered in a text box and dynamically display the result elsewhere on the page.
As I said, this would preferably be done in jQuery or Javascript.
Thanks in advance.

You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
UPDATE: jsFiddle (by Dreami)
UPDATE 2: Updating to include keydown for long presses.

This is my preference:
<textarea></textarea>
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>
Then jquery block
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}

<script type="text/javascript">
function countChars(countfrom,displayto) {
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
</script>
<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.
Plain Javascript.

I would like to share my answer which i used in my project and it is working fine.
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="4" Columns="50" placeholder="Maximum limit: 100 characters"></asp:TextBox><br />
<span id="spnCharLeft"></span>
<script type='text/javascript'>
$('#spnCharLeft').css('display', 'none');
var maxLimit = 100;
$(document).ready(function () {
$('#<%= txtComments.ClientID %>').keyup(function () {
var lengthCount = this.value.length;
if (lengthCount > maxLimit) {
this.value = this.value.substring(0, maxLimit);
var charactersLeft = maxLimit - lengthCount + 1;
}
else {
var charactersLeft = maxLimit - lengthCount;
}
$('#spnCharLeft').css('display', 'block');
$('#spnCharLeft').text(charactersLeft + ' Characters left');
});
});
</script>
Source: URL

Though it has been already solved, I'm interested to share something that I have used in one of my projects:
<textarea id="message" cols="300" rows="200" onkeyup="countChar(this)"
placeholder="Type your message ..." >
</textarea>
<input id="text-character" class="input-mini uneditable-input"
placeholder="0 Chars" readonly />
<input id="text-parts" class="input-mini uneditable-input"
placeholder="0 Parts" readonly />
<input id="text-remaining" class="input-medium uneditable-input"
placeholder="160 Chars Remaining" readonly />
Javascript code:
function countChar(val) {
var len = val.value.length;
var ctext = len + " Chars";
var str = val.value;
var parts = [];
var partSize = 160;
while (str) {
if (str.length < partSize) {
var rtext = (partSize - str.length) + " Chars Remaining";
parts.push(str);
break;
}
else {
parts.push(str.substr(0, partSize));
str = str.substr(partSize);
}
}
var ptext = parts.length + " Parts";
$('#text-character').val(ctext);
$('#text-parts').val(ptext);
$('#text-remaining').val(rtext);
}

<script Language="JavaScript">
<!--
function Length_TextField_Validator()
{
var len = form_name.text_name.value.length; //the length
return (true);
}
-->
</script>
<form name="form_name" method="get" action="http://www.codeave.com/html/get.asp"
onsubmit="return Length_TextField_Validator()">
<input type="text" name="text_name">
<input type="submit" value="Submit">
</form>
Source(s) : Text Validation

Related

Make a button submittable more than once

So I found a script that can generate your link when you want to, here it is (credits to the owner!)
function CreateAffiliateLink(F) {
var findstring = "XXXXX";
var ts = 'var replacewith=document.' + F.name + '.AffCode.value';
eval(ts);
if (replacewith.length < 1) {
return;
}
var re = new RegExp(findstring, "g")
for (i = 0; i < F.length; i++) {
var s = new String(F.elements[i].value);
if (s.length > 0) {
var newstr = s.replace(re, replacewith);
F.elements[i].value = newstr;
}
}
}
<form name="me">
<p>
Type your affiliate code in the box and click the button:
<input type="text" name="AffCode" size="17">
<input type="button" value="Personalize links with my affiliate code" onClick="CreateAffiliateLink(this.form)">
</p>
<p>
Image link:<br>
<textarea name="a" cols="46" rows="3" wrap="off">
<a href="http://example.com/master/#XXXXX
<img src="http://example.com/image.jpg">
</a>
</textarea>
</p>
<p>
An ezine text link:<br>
<input type="text" name="b" size="46" value="http://example.com/master/#XXXXX">
</p>
</form>
But right now, when I use it, I have to refresh everytime I want to put a new value. I wanted to find a way on how I can generate more than once without having to refresh the page.
I tried editing some part of it but it's still only usable once. Is there a way to change that?
It's because findstring is always 'XXXXX' (it looks for value, which changes after click).
Replace old code with:
var findstring = "XXXXX";
function CreateAffiliateLink(F) {
var replacewith = F.AffCode.value;
if (replacewith.length < 1) return;
var re = new RegExp(findstring, "g")
for (i = 0; i < F.length; i++) {
var s = F.elements[i].value.toString();
if (s.length > 0) {
var newstr = s.replace(re, replacewith);
F.elements[i].value = newstr;
findstring = replacewith;
}
}
}
The reason it only works once is because it's looking for XXXXX in the URL, and replacing that with the affiliate code. But after you do a replacement, the URL no longer has XXXXX.
Use a more general regular expression that will match the master/# in the URL, and replace everything after it.
function CreateAffiliateLink(F) {
var replacewith=F.AffCode.value;
if (replacewith.length < 1) {
return;
}
replacewith = 'master/#' + replacewith;
var re = /master\/#\w+/g;
for (i = 0; i < F.length; i++) {
var s = new String(F.elements[i].value);
if (s.length > 0) {
var newstr = s.replace(re, replacewith);
F.elements[i].value = newstr;
}
}
}
<form name="me">
<p>
Type your affiliate code in the box and click the button:
<input type="text" name="AffCode" size="17">
<input type="button" value="Personalize links with my affiliate code" onClick="CreateAffiliateLink(this.form)">
</p>
<p>
Image link:<br>
<textarea name="a" cols="46" rows="3" wrap="off">
<a href="http://example.com/master/#XXXXX">
<img src="http://example.com/image.jpg">
</a>
</textarea>
</p>
<p>
An ezine text link:<br>
<input type="text" name="b" size="46" value="http://example.com/master/#XXXXX">
</p>
</form>

how to insert id="getdobval" into input value?

I want to insert a value into <input type="text" id="getdobtval"> when I am selecting a range value.
For showing output in browser am using <span id="getdobtval"></span> instead of this span I want insert into text. How can I solve this using javascript?
jQuery(document).ready(function() {
$('#slider-bottom').slider().on('slide', function(ev) {
var finalvalue = '';
var finalbtvalue = '';
var finalbtprice = '';
var finalbitvalue = '';
finalbtprice = 250;
var newVal = $('#slider-bottom').data('slider').getValue();
var textval = parseInt(newVal);
if (textval >= 600 && textval < 6000) {
finalvalue = 0.075;
finalbitvalue = textval * finalvalue;
} else if (textval >= 6000 && textval < 30000) {
finalvalue = 0.070;
finalbitvalue = textval * finalvalue;
} else if (textval >= 30000) {
finalvalue = 0.065;
finalbitvalue = textval * finalvalue;
}
finalbtvalue = finalbitvalue / finalbtprice;
if (finalbtvalue) {
$("#getdobtval").html("<strong>" + finalbtvalue.toFixed(8) + "</strong>");
}
});
$('#slider-bottom').sliderTextInput();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<input id="slider-bottom" type="text" name="hrate" data-slider-min="600" data-slider-max="100000" data-slider-step="1" data-slider-value="600" data-slider-tooltip="show" />
<span id="getdobtval"></span>
<input type="text" id="getdobtval" name="getdobtval">
<input type="submit" name="buynow">
</form>
Create a hidden input box with different id like dobtval
<form action="" method="post">
<input id="slider-bottom" type="text" name="hrate" data-slider-min="600" data-slider-max="100000" data-slider-step="1" data-slider-value="600" data-slider-tooltip="show" />
<span id="getdobtval"></span>
<input type="hidden" id="dobtval" name="dobtval"/>
<input type="submit" name="buynow">
</form>
And in JS use,
....
if (finalbtvalue) {
$('#dobtval').val(finalbtvalue.toFixed(8));// set value in input
$("#getdobtval").html("<strong>" + finalbtvalue.toFixed(8) + "</strong>");
}
....
id must be unique, but if you want same HTML then differentiate your elements by their tag name like,
$('span#getdobtval').html('....'); // use html() span/div
$('input#getdobtval').val('....'); // use val() for input/textarea

dynamically count textarea symbols in a simple input

Good day everyone
I have a simple textarea on a page,and I need to dynamically count number of symbols, show how much is left under the form,and limit number of characters should be 350.
Thanks in advance.
What i exactly need is to display how many symbols are left to type
function limit(element)
{
var max_chars = 350;
if(element.value.length > max_chars) {
element.value = element.value.substr(0, max_chars);
}
}
<textarea onkeydown="limit(this);" onkeyup="limit(this);"></textarea>
var max_chars = 5;
var charsLeftDisplay = document.getElementById("charsLeft");
function limit(element) {
if (element.value.length > max_chars) {
element.value = element.value.slice(0, -1);
return false;
}
charsLeftDisplay.innerHTML = (max_chars - element.value.length) + " characters left...";
}
<textarea onkeyup="limit(this)"></textarea>
<p id="charsLeft"></p>
I think the best way to do this would be to use JQuery
here's the html
<textarea id="textareaID" rows="4" cols="50" maxlength="50"></textarea>
<p id="numberOfChars"><strong>Character typed:</strong> 0</p>
<p><strong>Max Character:</strong> 50</p>
and here's the jquery code
$('#textareaID').bind('input propertychange', function() {
if(this.value.length){
$("#numberOfChars").html("<strong>Character typed:</strong> "+this.value.length);
}
});
and here's a working fiddle as well https://jsfiddle.net/Visrozar/zbw7j64j/
Here is a simple solution,
just display the leftCharacters in a placeholder;
<script>
$(function() {
var $textarea = $('textarea');
var $input = $('input[name="spaces"]');
var maxLength = $textarea.attr('maxlength');
$input.val(maxLength);
$textarea.on('input', function() {
var currentLength = $textarea.val().length;
var leftCharacters = (maxLength - currentLength);
$input.val(leftCharacters);
});
});
</script>
<textarea name=test" maxlength="350"></textarea>
<input name="spaces" disabled />
This solution really works very well:
1 - Insert a div with id="textarea_count" for example in the place you want to show remaining characters, in your HTML file, near your textarea element (above or under):
<div class="form-group">
<label asp-for="DescCompetencia" class="col-md-2 control-label"></label>
<div class="col-md-10">
<textarea asp-for="DescCompetencia" class="form-control" rows="5"></textarea>
<span asp-validation-for="DescCompetencia" class="text-danger"></span>
<div id="textarea_count"></div>
</div>
</div>
2 - Insert in your javascript file or after /html element in the page you are editing the textarea element:
$(document).ready(function () {
var text_max = 500; //change by your max desired characters
var text_min = 7; //change to your min desired characters (or to zero, if field can be blank))
if ($('#DescCompetencia').length) {
var texto_disponivel = text_max - $('#DescCompetencia').val().length;
}
$('#textarea_count').html(texto_disponivel + ' caracteres disponíveis para digitar');
$('#DescCompetencia').keyup(function () {
var text_length = $('#DescCompetencia').val().length;
var text_remaining = text_max - text_length;
if (text_length <= text_min) {
$('#textarea_count').html(text_remaining + ' caracteres remanescentes. Digite ' + text_min + ' ou mais caracteres.');
}
else {
$('#textarea_count').html(text_remaining + ' caracteres remanescentes');
}
}); });
Must have Jquery already loaded before calling the above function.

Javascript won't calculate

Can anyone point me in the right direction as to why my calculate button will not calculate. It doesn't even throw any of the error messages up to the screen, but my clear button does work. It's probably something small, but I cannot figure it out for the life of me -_-.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("totalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("cost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
var virusRemoval = parseFloat($("virusRemoval").value = "");
var websiteMaking = parseFloat($("websiteMaking").value = "");
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value = "");
var totalCost = parseFloat($("totalCost").value = "");
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotal" value="Calculate " onblur="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
The reason why the loop is in there is because we were required to have a loop and I couldn't find a good reason to have one, so I used one that would always be true to get it out of the way lol. Probably will throw an infinate loop at me or something, but I'll figure that out later, I'm just trying to get the dang on thing to do something here haha. I've tried to rewrite this 2 other times and still get to the same spot, so I realize it's probably something small, and I am new to Javascript. Thank you.
The problem is that you have id="calculateTotal" in the input button. Element IDs are automatically turned into top-level variables, so this is replacing the function named calculateTotal. Simply give the function a different name from the button's ID.
You also have a typo. The ID of the Total Cost field is TotalCost, but the code uses $('totalCost') and $('cost').
It's also better to do the calculation in onclick, not onblur. Otherwise you have to click on the button and then click on something else to see the result.
In the clearValues function, there's no need to assign variables and call parseFloat. Just set each of the values to the empty string. You could also just use <input type="reset">, that resets all the inputs in the form to their initial values automatically.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("TotalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("TotalCost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
$("virusRemoval").value = "";
$("websiteMaking").value = "";
$("computerOptimizationAndSetUp").value = "";
$("TotalCost").value = "";
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotalButton" value="Calculate " onclick="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>

JavaScript hiding plain text similar to password

I am trying to hide/show the plain text of a hashing function, I have been able to hide the input field but i have not been able to hide/show the plain text, the webpage has a input field and under that is the text that i am typing, then there is the hashed text, i am trying to replace the plain text with bullets.
I tried hiding it by counting the number of characters in the field and then repeating the bullet that many times. but now the page does not function at all.
<!DOCTYPE html>
<html>
<body>
<input
name="show password"
type="checkbox"
checked="checked"
onclick="toggleType();" />
<input
size="80"
input type="text"
rows="7"
id="edValue"
type="text"
onKeyPress="edValueKeyPress()
"onKeyUp="edValueKeyPress()">
<p id="string">Original text: </p>
<p id="lblValue">The SHA256 hash is: </p>
<script type="text/javascript" src="sha256.js">
</script>
<script type="text/javascript">
function edValueKeyPress()
{
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
lblValue.innerText = "The SHA256 hash is: "+sha256_digest(s);
var TheText = document.getElementById("string");
TheText.innerText = "Original text: "+s;
}
function toggleType() {
var obj = document.getElementById('edValue');
if (obj.type == 'password') {
obj.type = 'text';
} else {
obj.type = 'password';
repeat();
}
}
function repeat() {
var length = this.value.length;
var count = document.getElementById("edValue");
String.prototype.repeat = function(n) {
return new Array(1 + n).join(this);
var TheText = document.getElementById("string");
TheText.innerText = "*".repeat(count);
}
</script>
</body>
</html>
Just use a regex:
w/ jQuery:
$('YOURELEMENT').html($('div').html().replace(/./g, '*'));
without:
var text = document.getElementById('YOURELEMENT').innerText;
document.getElementById('string').innerHTML = text.replace(/./g, '*')
To toggle :
Html input
<input
name="show password"
type="checkbox"
checked="checked"
onclick="toggleType();" />
<input id="password" type="password" />
The javascript
function toggleType(){
var inputEl = document.getElementById('password');
if(inputEl.type != "text"){
inputEl.type = "text";
}else{
inputEl.type = "password";
}
}
Working example: http://jsfiddle.net/3MRAX/1/
Sorry about this, OP, but I tried :( This is as far as I got.
Javascript
function edValueKeyPress()
{
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
var hashes = s.hashCode;
lblValue.innerHTML = "The SHA256 hash is: " + hashes;
var text = document.getElementById("string");
text.innerHTML = "Original text: " + s;
}
function toggleType() {
var obj = document.getElementById('edValue');
if (obj.type == 'password') {
obj.type = 'text';
} else if(obj.type == 'text'){
obj.type = 'password';
}
}
HTML
<input
name="show password"
type="checkbox"
checked="checked"
onclick="toggleType();" />
<input
size="80"
type="text"
rows="7"
id="edValue"
type="text"
onkeyup="edValueKeyPress();">
<p id="string">Original text: </p>
<p id="lblValue">The SHA256 hash is: </p>

Categories

Resources