How to count number of words in a textfield - javascript

I have a user enter biograpgy in a text box html for that is
<p>Biography:
<input type="text" id="biography" name="biography" />
<span id="biographyInvalid" style="color:red; visibility:hidden"> Biography is Invalid </span>
</p>
for Javascript i have a checkme function that is called and i want to do a check inside of it
function checkme(){
var biography=document.getElementById('biography').value;
}
how can i count number of words, do i first convert it to string and then separate with spaces

<div>
<div id="count">145</div>
<div id="barbox"><div id="bar"></div></div>
</div>
<textarea id="contentbox"></textarea>
and js
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#contentbox").keyup(function()
{
var box=$(this).val();
var main = box.length *100;
var value= (main / 145);
var count= 145 - box.length;
if(box.length <= 145)
{
$('#count').html(count);
$('#bar').animate(
{
"width": value+'%',
}, 1);
}
else
{
alert(' Full ');
}
return false;
});
});
</script>
$('#contentbox').keyup(function(){} - contentbox is the ID of the textbox.
Using $(this).val() getting the textbox value.
bar is the div ID of the count meter $('#bar').animate() increasing the width.

js:
$('#biography').keyup(function () {
var words = this.value.match(/\S+/g).length;
$('#count').html('Words Count:'+words);
});
HTML:
<div id="count"></div>
This gives you correct words count

This is working example
the HTML
<form name="myform" method="post" action="">
<textarea name="inpString" cols="80" rows="4" onkeyup="countNoOfWords()" >This is a sample text that has been typed to count the number of words it contains. Click the button below to find out.</textarea>
<br />
<input name="noofwords" type="text" value="" size="6" />
</form>
The JS function
<script type="text/javascript">
function countNoOfWords(){
document.myform.noofwords.value = document.myform.post_content.value.split(' ').length;
}
</script>
reference

$('input').keyup(function() {
var cs = this.value.match(/\S+/g).length;
$('#biography').text(cs);
});
Demo - http://jsfiddle.net/hNn5b/685/

Related

how to show content in multiple classes with javascript

I am using tinymce for a textarea and i want to cout the characters inside of it.
Now i use this code:
<textarea class="tinymce" rows="2" cols="20"></textarea>
<br />
<div class="character_count"></div>
<textarea class="tinymce" rows="2" cols="20"></textarea>
<br />
<div class="character_count"></div>
<textarea class="tinymce" rows="2" cols="20"></textarea>
<br />
<div class="character_count"></div>
<script type="text/javascript">
tinymce.init({
selector: '.tinymce',
width: 400,
setup: function (ed) {
ed.on('keyup', function (e) {
var count = CountCharacters();
var x = $(".character_count");
x[0].innerHTML = "Characters: " + count;
});
}
});
function CountCharacters() {
var body = tinymce.activeEditor.getBody();
var content = tinymce.trim(body.innerText || body.textContent);
return content.length;
};
</script>
This works fine, except the number of characters is displayed only in the first div (because of x[0]
is it possible to show, whatever textarea i am typing in, to display the characters in ever div <div class="character_count"></div> ?
Yes, relace this line x[0].innerHTML = "Characters: " + count; with this
x.each( function() { $(this).text("Characters: " + count); });
const p = $("p")
$("input").on("input", function(e) {
p.each(function() {
$(this).text(e.target.value)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" />
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>

Writing single JS script for assigning ID's to output in HTML

I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>

Creating input element continuing ID enumeration

I have a button that creates 4 input elements inside a DIV after click:
<div id="content"></div>
<button class="check">Check</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var num = 4;
$(".check").click(function(){
for(i=0; i<num;i++){
$("#content").append("<input id='input"+i+"' type='text'><br>");
}
});
</script>
But the problem is I want input id number continues the enumeration (like this example) instead of return to zero:
<div id="content">
<input id="input0" type="text">
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
<input id="input4" type="text">
<input id="input5" type="text">
<input id="input6" type="text">
<input id="input7" type="text">
...and continues
</div>
How can I fix it?
You can check the id of the last input. Here I am calculating start and end of for loop based on the total number of elements in #container.
var num = 4;
$(".check").click(function() {
var start = $("#content input").length;
var end = start + num;
for (i = start; i < end; i++) {
var id = 'input' + i;
$("#content").append("<input id='"+id+"' type='text' value='"+id+"'><br>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<button class="check">Check</button>
PS: Here input value is just to demonstrate the id setting to input.
You need some kind of global variable here, or use that simple one:
var getID = (function () {
var id = 0;
return function () { return ++id; }
})();
So whenever you call getID() the »internal« id will be incremented, so each call will yield an new ID.
$(".check").click(function() {
for(var i = 0; i < 4; i++) {
$('<input type="text">') //create a new input
.attr('id', 'input' + $('#content input').length) //id based on number of inputs
.appendTo('#content'); //append it to the container
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<button class="check">Check</button>
If you're asking how to have a stack of elements to begin with, and then continue enumeration from there, you simply need to set a variable to the ID of the latest element.
All you need to do is count the number of elements. This can be done with a combination of .querySelectorAll() and .length.
Then simply have your loop start at this new value instead of 0.
This can be seen in the following:
var total_desired = 20;
var start = document.querySelectorAll('#content > input').length;
console.log(start + " elements to start with");
$(".check").click(function() {
for (i = start; i < total_desired; i++) {
$("#content").append("<input id='input" + i + "' type='text'><br>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="check">Check</button>
<div id="content">
<input id="input0" type="text">
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
<input id="input4" type="text">
<input id="input5" type="text">
<input id="input6" type="text">
<input id="input7" type="text"> ...and continues
</div>
Having said that, it's unlikely that you actually need simultaneous ID <input> elements, and you may benefit from classes instead.
You can create this object:
var MyId = {
a: 0,
toString() {
return this.a++;
}
}
And concatenate it into the string. Automatically will increase the counter.
<div id="content"></div>
<button class="check">Check</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var GetID = {
a: 0,
toString() {
return this.a++;
}
}
var num = 4;
$(".check").click(function(){
for(i=0; i<num;i++){
$("#content").append("<input id='input"+GetID+"' type='text'><br>");
}
});
</script>

Updating same html Element with jQuery when user input changes

I am trying do some calculations that take user input and supply the calculated value for the user to see. The user will supply two values and then the result, ADF, will be returned.
Two problems that I am having: The value is calculated before I have entered the second value (FG); and when either value is changed, the old ADF is not replaced. I understand that is because it keeps applying .append(), but I do not know what I need to use instead. I have provided pictures of what is happening. I have listed my code below.
*Note the round() and ADF() functions are my Javascript functions used for the calculations and I didn't think it relevant to list that code. Let me know if you think it is relevant to see it.
Thanks in advance for your help.
function main() {
$(document).on('change', '#Gravities', function () {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
var calc = round(ADF(OG,FG)*100, 2);
$('.ADFbox').append('<div class="ADF">'+calc+'%</div>');
});
}
$(document).ready(main);
<body>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' name='FG' value=""></input></label></p>
</div>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>
</body>
</html>
enter image description here
enter image description here
$(document).on("input", ".gravity", function() {
var thisval = $(this).val()
var nothisval = $(".gravity").not(this).val()
if (thisval.length > 0 && nothisval.length > 0) {//check if one value is empty
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
//var calc = round(ADF(OG, FG) * 100, 2);
var calc = OG * FG;//change this computation
//$('.ADFbox').append('<div class="ADF">' + calc + '%</div>');
$('.ADFbox').text("ADF:" + calc).change();
} else {
$('.ADFbox').text("ADF: 0");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' class="gravity"name='OG' value ="" /></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' class="gravity" name='FG' value=""/></label></p>
</div>
</form>
<div class='ADFbox'>
<p>ADF:</p>
</div>
</body>
Check of each value then proceed if both value has length more than 0
Note: input has no ending tag just close like <input />
To solve this you could place the .adf div in the HTML on load and then simply update it's text() instead of using append() to create a new copy after each calculation.
Below is a working example. Note that I simplified the calculation as you didn't provide the logic of the round() or ADF() functions. Try this:
function main() {
$(document).on('change', '#Gravities', function() {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
//var calc = round(ADF(OG, FG) * 100, 2);
var calc = OG * FG;
$('.ADFbox .adf').text(calc + '%');
});
}
$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Gravities">
<div>
<p>
<label class="originalGravity">
OG:
<input type='text' name='OG' value="">
</label>
</p>
</div>
<div>
<p>
<label class="finalGravity">
FG:
<input type='text' name='FG' value="">
</label>
</p>
</div>
</form>
<div class='ADFbox'>
<p>ADF: <div class="adf"></div></p>
</div>
The problem you are appending html not updating the existing text value.
Just change your code like below:
$(document).on('change', '#Gravities', function () {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
if(OG != "" && FG != ""){
var calc = round(ADF(OG,FG)*100, 2);
$('.ADFbox').find("p").html("ADF:"+ calc + '%');
}
});
function main() {
$(document).on('change', '#Gravities', function () {
if($('input[name=OG]').val()!='' && $('input[name=FG]').val()!=''){
var calc = round(ADF(OG,FG)*100, 2);
$('.ADFbox').html('<div class="ADF">'+calc+'%</div>');
}
});
}
$(document).ready(main);
<body>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' name='FG' value=""></input></label></p>
</div>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>
</body>
</html>
You have added on change event. that's why it's getting calculated each time when any one of the fields got updated. I made few changes:
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='number' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='number' name='FG' value=""></input>
</label></p>
</div>
<button type="button" id="fgs">
Find ADF</button>
</button>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>
function main() {
$("#fgs").on('click', function () {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
var calc = OG*FG;
document.getElementsByClassName("ADFbox")[0].innerHTML= "ADF:"+" " +calc;
});
}
$(document).ready(main);
created working fiddle for you: https://jsfiddle.net/Safoora/hspdgqca/15/
Sorry if I'm not understanding you. As per my understanding you need to calculate only if both inputs field are changed? If it is so, you can do like this:
function main() {
$(document).on('change', '#Gravities input', function () {
OG = $('input[name=OG]');
FG = $('input[name=FG]');
$(this).data('changed',true); // set "changed=true" for current input
// Check if both input fields are changed
if(OG.data('changed') == true && FG.data('changed') == true){
//var calc = round(ADF(OG.val(),FG.val())*100, 2); // uncomment this
var calc = OG.val() * FG.val(); // comment this
$('.ADFbox').html(function(){
$('#Gravities input').data('changed',false); // set "changed=false" for next query
return '<div class="ADF">'+calc+'%</div>'
});
}
});
}
$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' name='FG' value=""></input></label></p>
</div>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>

How can I add values of form textbox using string ,for loop

hi guys i am new to js and html.I need a o/p as when click the button tat should show the all contents entered in form...
My code for giving alert of all entered data in single
how can I add values of form textbox using string ,for loop all should be only in javascript...or else give your own code with the conditions i said....
<html>
<head>
<title>elements in a form</title>
<script type="text/javascript">
function processFormData()
{
var len= document.getElementsByTagName('name');
var str1=null;
for(i=0;i<=len;i++)
{
var str=(subscribe.name[i].value);
str=str1+str;
}
alert(str);
}
</script>
</head>
<body>
<form name ="subscribe" >
<p><label for="name">Your Name: </label><input type="text" name="name" id="txt_name" value="name"></p>
<p><label for="email">Your Email: </label><input type="text" name="email" id="txt_email" value="mail"></p>
<input type="button" value="submit" onclick="processFormData()">
</form>
</body>
</html>
Try that for a start
var len= document.getElementsByTagName('input').length;
// add that you want the number of element
// Change 'name' for 'input' when using 'name' you are looking for <name in the HTML
// if you want the element with the name ABC use getElementsByName()
var str1='';
for(i=0;i<=len;i++)
{
var str=(subscribe[i].value);
str1=str1+str;
}
alert(str1);
jsFiddle example (in jQuery for the calling of the function) : http://jsfiddle.net/DavidLaberge/HPuhg/1/
<html>
<head>
<title>elements in a form</title>
<script type="text/javascript">
var str1=null;
function processFormData()
{
var len= document.getElementsByTagName('name').length;
for(i=0;i<=len;i++)
{
var str=(subscribe.name[i].value);
str1=str1+str;
}
alert(str1);
}
</script>
</head>
<body>
<form name ="subscribe" >
<p><label for="name">Your Name: </label><input type="text" name="name" id="txt_name" value="name"></p>
<p><label for="email">Your Email: </label><input type="text" name="email" id="txt_email" value="mail"></p>
<input type="button" value="submit" onclick="processFormData()">
</form>
</body>
</html>
you have just minor mistake that is you used str in place of str1; Now use the above code.
Try something like:
function processFormData() {
var inputs = document.getElementsByTagName("input"),
i,
len,
stringBuffer = [],
str;
for (i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type.toLowerCase() === "text") {
stringBuffer.push(inputs[i].value);
}
}
str = stringBuffer.join(""); // str contains concatenated values of all inputs
}
Try this:
function processFormData()
{
var len= document.getElementsByTagName('input').length;
var str = '';
for(i=0;i<len-1;i++)
{
str += document.subscribe[i].value;
}
alert(str);
}

Categories