Can somebody explains that why my input fields value is not changing - javascript

I am making a simple word counter program in JavaScript. I am fairly new in JavaScript world so excuse me if I am asking an rudimentary and simple enough question. I'm getting everything working that the string of text from textarea is splitted into words array and i can log number of words to console but can't display them into a text field where I want them to appear. Hope that someone can help here. Thanks
var btn = document.getElementById("btn");
var numWords = document.getElementById("output");
var str = document.getElementById("txtBox");
btn.onclick = function()
{
var words = str.value.split(" ");
numWords.innerHTML.value = words.length;
console.log( words.length );
};
.container
{
width: 600px;
margin: 0 auto;
}
textarea
{
width: 560px;
padding: 10px;
background-color: #dfdfdf;
color: #333;
font-size: 18px;
}
input
{
text-align: center;
padding: 10px;
margin-top: 15px;
}
input[type="submit"]
{
float: right;
margin-right: 15px;
background-color: #84ac49;
border: 0;
color: #fff;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="container">
<from>
<textarea name="txtBox" id="txtBox" cols="30" rows="10"></textarea><br/>
<input type="text" value = 0 id="output">
<input type="submit" value="Count Words" id="btn">
</from>
</div>
</body>
</html>

move getting value in click function event
btn.onclick = function()
{
var str = document.getElementById("txtBox").value
var words = str.split(" ");
numWords.value = words.length;
console.log( words.length );
};
JSFIDDLE

btn.onclick = function () {
var words = str.value.split(" ");
numWords.value = words.length;
console.log(words.length);
};
also you can set input like this:
<input value="Count Words" id="btn">

when You click on count button You will get word count.
HTML
<textarea id="inputString" cols="50" rows="4"></textarea>
<br>
<input type="button" name="Convert" value="Count Words" onClick="countWords();">
<input id="wordcount" type="text" value="0" size="6">
Javascript
countWords=function(){
s=document.getElementById("inputString").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
document.getElementById("wordcount").value = s.split(' ').length;
}
Here is a demo :https://jsfiddle.net/DhwaniSanghvi/tdn3x72g/

Related

Javascript appended code comes as undefined

I have this code where I take the submissions from a form and append it to a HTML.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<style>
* {
box-sizing: border-box;
}
div {
padding: 10px;
background-color: #f6f6f6;
overflow: hidden;
}
input[type=text],
textarea,
select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type=button] {
font: 17px Calibri;
width: auto;
float: right;
cursor: pointer;
padding: 7px;
}
</style>
</head>
<body>
<div>
<div>
<input type="text" id="txtName" placeholder="Enter your name" />
</div>
<div>
<input type="text" id="txtAge" placeholder="Enter your age" />
</div>
<div>
<input type="text" id="txtEmail" placeholder="Enter your email address" />
</div>
<div>
<select id="selCountry">
<option selected value="">-- Choose the country --</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="USA">USA</option>
</select>
</div>
<div>
<textarea id="msg" name="msg" placeholder="Write some message ..." style="height:100px"></textarea>
</div>
<div>
<input type="button" id="bt" value="Write" onclick="writeFile()" />
</div>
</div>
<p>Submission Number: <a id="clicks">1</a>
<div class="output-area">
<h4>Output</h4>
<div id="output" class="inner">
</div>
</div>
<span></span>
</body>
<script>
var clicks = 1;
let writeFile = () => {
const name = document.getElementById('txtName');
const age = document.getElementById('txtAge');
const email = document.getElementById('txtEmail');
const country = document.getElementById('selCountry');
const msg = document.getElementById('msg');
const submissions = document.getElementById('clicks');
let data = [
`<p>Name: ${name.value}</p>`,
`<p>Age: ${age.value}</p>`,
`<p>Email: ${email.value}</p>`,
`<p>Country: ${country.value}</p>`,
`<p>Message: ${msg.value}</p>`,
`<p>Submission No: ${submissions.value}</p>`];
$('#output').append("<br />" + "<br />");
data.forEach(line => $('#output').append(line));
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
</script>
</html>
In this code, I wanted to print the users' current submission number. So I made a click counter.
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
And then I tried to put it into a constant and append it.
const submissions = document.getElementById('clicks');
But issue I'm facing here is, when appended my submission field comes out as Submission No: undefined. Any help would be much appreciated.
Your submissions element is an anchor (<a>) element. These HTML elements do not have a value field.
You can read the value the same way you are writing it, via innerHTML.
E.g.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<style>
* {
box-sizing: border-box;
}
div {
padding: 10px;
background-color: #f6f6f6;
overflow: hidden;
}
input[type=text],
textarea,
select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type=button] {
font: 17px Calibri;
width: auto;
float: right;
cursor: pointer;
padding: 7px;
}
</style>
</head>
<body>
<div>
<div>
<input type="text" id="txtName" placeholder="Enter your name" />
</div>
<div>
<input type="text" id="txtAge" placeholder="Enter your age" />
</div>
<div>
<input type="text" id="txtEmail" placeholder="Enter your email address" />
</div>
<div>
<select id="selCountry">
<option selected value="">-- Choose the country --</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="USA">USA</option>
</select>
</div>
<div>
<textarea id="msg" name="msg" placeholder="Write some message ..." style="height:100px"></textarea>
</div>
<div>
<input type="button" id="bt" value="Write" onclick="writeFile()" />
</div>
</div>
<p>Submission Number: <a id="clicks">1</a>
<div class="output-area">
<h4>Output</h4>
<div id="output" class="inner">
</div>
</div>
<span></span>
</body>
<script>
var clicks = 1;
let writeFile = () => {
const name = document.getElementById('txtName');
const age = document.getElementById('txtAge');
const email = document.getElementById('txtEmail');
const country = document.getElementById('selCountry');
const msg = document.getElementById('msg');
const submissions = document.getElementById('clicks');
let data = [
`<p>Name: ${name.value}</p>`,
`<p>Age: ${age.value}</p>`,
`<p>Email: ${email.value}</p>`,
`<p>Country: ${country.value}</p>`,
`<p>Message: ${msg.value}</p>`,
`<p>Submission No: ${submissions.innerHTML}</p>`]; // Use innerHTML here
$('#output').append("<br />" + "<br />");
data.forEach(line => $('#output').append(line));
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
</script>
</html>
Generally you could of course also insert the clicks variable directly (instead of the contents of the a element).
Note
It is highly insecure to render user-input into your HTML. It creates all sorts of vulnerabilities for malicious users so DON'T do this in production.
<a> tags don't have a value attribute. You'll have to use textContent or innerText to get the count.
console.log(document.getElementById('clicks').textContent);
<a id="clicks">2</a>
Ok, so submissions is not a input element and so it does not have the value method.
Instead of using submissions.value use submissions.innerHTML.
Also, rearrange the last few lines to make sure the clicks counter is updated before outputting all the data.
Edit: I did not realize your clicks counter was initially let clicks = 1; and not let clicks = 0;. The rearranging in the below JS will only work if clicks is initially set to 0.
I would generally advise to use let clicks = 0; because it makes more sense to potentially yourself and another person reading your code. If you think about it - when you make your counter (clicks), there have not been any clicks yet and so it would make more sense to have it initially set to 0.
let clicks = 0;
const writeFile = () => {
const name = document.getElementById('txtName');
const age = document.getElementById('txtAge');
const email = document.getElementById('txtEmail');
const country = document.getElementById('selCountry');
const msg = document.getElementById('msg');
const submissions = document.getElementById('clicks');
// ++ is same thing as += 1
clicks++;
submissions.innerHTML = clicks;
let data = [
`<p>Name: ${name.value}</p>`,
`<p>Age: ${age.value}</p>`,
`<p>Email: ${email.value}</p>`,
`<p>Country: ${country.value}</p>`,
`<p>Message: ${msg.value}</p>`,
`<p>Submission No: ${submissions.innerHTML}</p>`
];
$('#output').append("<br />" + "<br />");
data.forEach(line => $('#output').append(line));
}

Click Button To Get a Random Item Displayed in a Text Box in Javascript

So, my Mab Libs Program is working fine. The problem comes when I want to create a button to let the user display suggestions from an array. I am using this as the function:
function GetValue(myNameArray)
{
let myNameArray= new Array["item1","item2","item3"];
var randomName = myNameArray[Math.floor(Math.random() * myNameArray.length)];
document.getElementById("personOne") = randomName;
}
Then, when I go into it and test the code out, it will not show a result in the text box. There's nothing quite like this on the internet and the only results are for general arrays.
Thank you for your help.
Full Code I Am Using:
<html><head>
<title>
Mad Libs Story
</title>
<style>
h3 {
text-align: center;
}
#input {
text-align: center;
box-sizing: border-box;
width: 100%;
border: solid #5B6DCD 10px;
padding: 3px;
}
#madLibCreation {
text-align: center;
box-sizing: content-box;
width: 100%;
border: solid #FFFFFF;
padding: 3px;
font-weight: bold;
font-size: 24px;
}
</style>
<script>
function getVars() {
var firstPerson = String(document.getElementById("personOne").value);
var firstAdjective = String(document.getElementById("adjectiveOne").value);
var secondAdjective = String(document.getElementById("adjectiveTwo").value);
var thirdAdjective = String(document.getElementById("adjectiveThree").value);
var secondPerson = String(document.getElementById("personTwo").value);
var fourthAdjective = String(document.getElementById("adjectiveFour").value);
var firstNumber = Number(document.getElementById("numberOne").value);
var thirdPerson = String(document.getElementById("personThree").value);
document.getElementById("madLibCreation").innerHTML = "Dear " + firstPerson + ", Overall, Camp Ad-Lib is " + firstAdjective + ". The camp counselors are " + secondAdjective + " and the food is " + thirdAdjective + ". Today, I met someone named " + secondPerson + "and we became " + fourthAdjective + " friends. I hope to write to you in " + firstNumber + " days. Sincerely, " + thirdPerson + ".";
}
function GetValue(myNameArray)
{
let myNameArray= new Array["item1","item2","item3"];
var randomName = myNameArray[Math.floor(Math.random() * myNameArray.length)];
document.getElementById("personOne") = randomName;
}
</script>
</head>
<body>
<h3>
Welcome to "A Letter From Camp"! Have fun!
</h3>
<div id="input">
<p>
Name of Person in Room: <input type="text" id="personOne"> <input type="button" value="random" onclick="getValue();">
</p>
<p>
Adjective: <input type="text" id="adjectiveOne">
</p>
<p>
Adjective: <input type="text" id="adjectiveTwo">
</p>
<p>
Adjective: <input type="text" id="adjectiveThree">
</p>
<p>
Name of Someone: <input type="text" id="personTwo">
</p>
<p>
Adjective: <input type="text" id="adjectiveFour">
</p>
<p>
Number: <input type="text" id="numberOne">
</p>
<p>
Name of Someone: <input type="text" id="personThree">
</p>
<p>
<input type="submit" value="Get My MadLib Creation!" onclick="getVars();">
</p>
</div>
<p id="madLibCreation"></p>
</body></html>
There a few syntax errors in your code. The get in the function name should be lowercase, and remove the parameter.
function getValue()
{
var myNameArray = ["item1", "item2", "item3"];
var randomName = myNameArray[Math.floor( Math.random() * myNameArray.length )];
document.getElementById( "personOne" ).value = randomName;
}
If you put this in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
you can just do this:
document.getElementById("personOne").value = rando(["item1", "item2", "item3"]).value;
This implements randojs.com to make the randomness shorter and more readable.

Adding labels to QR codes

I have created a QR code generator. The user can create multiple QR codes.
I would like the user to be able to name each QR code (referred to as a checkpoint) by writing the desired checkpoint name in the text input field, clicking the Assign Name button and having the text input field disappear, being replaced by the name the user typed into the field.
The user can input checkpoint names, however, it only works for the first QR code printed, and the label only appears below the QR code. Below is the code that I have so far. Any help or suggestions to help me get the ball rolling on this would be very much appreciated. Thank you!
Note: If you try to run this to see the QR codes, you will have to enter something in the text field and press generate. They won't appear automatically.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: arial, sans-serif;
}
section {
margin: 50px auto;
max-width: 350px;
text-align: center;
}
textarea {
width: 50%;
height: 50px;
margin-bottom: 10px;
}
#size {
max-width: 64px;
}
label {
display: inline-block;
width: 140px;
text-align: left;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<section>
<h1>QR Code Generator</h1>
<p>Enter a URL or some text bellow and hit the Generate button (<kbd>Ctrl</kbd>+<kbd>Enter</kbd>)!</p>
<textarea id="textarea" autofocus></textarea>
<div class="block">
<label for="size">Size (px):</label>
<input align="left" id="size" type="number" value="150" min="50" max="500" step="50">
<label for="amount">Amount of Labels:</label>
<input align="left" id="amount" type="number" value="1" min="1" max="500" step="1">
<button id="genQRcode">Generate</button>
</div>
<div id="content" style="display: none;"></div>
</section>
<p id="demo" align="center"></p>
<script>
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<script id="template-qr-code" type="text/html">
<p> <img id="qrcode" src="{{src}}" /></p>
<label for="checkpoint"> Checkpoint Name:</label>
<input id="cpname" type="text" value="">
<button onclick="myFunction()">Assign Name</button>
</script>
<script type="text/javascript">
window.addEventListener('load', function() {
var textarea = document.getElementById("textarea"),
content = document.getElementById("content"),
amount = document.getElementById("amount"),
qrTemplate = document.getElementById('template-qr-code');
function genQRcode() {
var data = encodeURIComponent(textarea.value),
size = document.getElementById("size").value,
chart = "http://chart.googleapis.com/chart?cht=qr&chs=" + size + "x" + size + "&choe=UTF-8&chld=L|0&chl=" + data;
if (data === "") {
alert("Please enter valid data!");
textarea.focus();
content.style.display = "none";
} else {
for (var i = 0; i < amount.value; i++) {
var qrSrc = qrTemplate.innerHTML;
qrSrc = qrSrc.replace(new RegExp('{{src}}', 'g'), chart);
qrSrc = qrSrc.replace(new RegExp('{{i}}', 'g'), i);
content.insertAdjacentHTML('beforeEnd', qrSrc);
}
content.style.display = "";
}
}
document.getElementById("genQRcode").addEventListener("click", genQRcode);
document.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.keyCode == 13) {
genQRcode();
}
});
});
</script>
</body>
</html>
Your click function
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
is getting and setting an element by ID. That will only ever affect a single element on the page (usually the first one that the browser runs into with that specific id). You need to use a different selector / way of getting the label you want to change because you can't reuse ids.
Basically you need to make your label fields distinct so you can actually select them

Javascript needed for form reset button

I have a form with a text area as well as javascript counter that counts how many characters you type into the text area. I need a button that resets both whats typed into the text area AND the counter.
This is my form code:
<script type="text/javascript">
function change (el) {
var max_len = el.name == 'left' ? 60 : 320;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
}
document.getElementById(el.name + '_char_cnt').innerHTML = el.value.length;
document.getElementById(el.name + '_chars_left').innerHTML = max_len -
el.value.length;
return true;
}
</script>
<h2 style="background-color: #eee; padding: 10px 20px 10px 20px; margin-
bottom: 20px;">Enter meta title tag</h2>
<form id="title">
<textarea style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2" maxLength="60" onkeyup="change(this);"></textarea>You've typed <span id="left_char_cnt"><b>0</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b>lots</b></span> more
<input class="btn btn-primary" type="button" value="reset title" />
</form>
The javascript below resets the text entered into the textarea but it does not reset the counter within the span "left_char_cnt"
<script>
function myFunction() {
document.getElementById("title").reset();
}
</script>
What javascript is needed to reset both?
You cannot "reset" the text / HTML of an element if you haven't saved it somehow. reset() only works for form inputs.
So what you have to do is rewrite the HTML content of your element.
<script>
function myFunction() {
document.getElementById("title").reset();
document.getElementById("left_char_cnt").innerHTML = '<b>0</b>';
}
</script>
your script to count words in text is not working but, i made a script to clear textarea & count
function myfun(){
document.getElementById('txtarea').value=' ';
document.getElementById('count').innerHTML='0';
}
<form id="title">
<textarea id="txtarea" style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2"></textarea>You've typed <span id="left_char_cnt"><b id=count>123</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b >lots</b></span> more
<input class="btn btn-primary" type="button" onclick="myfun()" value="reset title" />
</form>
<script type="text/javascript">
function change (el) {
var max_len = el.name == 'left' ? 60 : 320;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
}
document.getElementById(el.name + '_char_cnt').innerHTML = el.value.length;
document.getElementById(el.name + '_chars_left').innerHTML = max_len -
el.value.length;
return true;
}
</script>
The simplest way is to reuse the code you already have, and allow the change event handler to set the values correctly. That way, if you ever change the behavior of that function then the reset will also change to match it.
I also modified your code slightly to make it update as the text is changing, rather than when you leave the textarea.
Try this...
function change (el) {
var max_len = el.name == 'left' ? 60 : 320;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
}
document.getElementById(el.name + '_char_cnt').innerHTML = el.value.length;
document.getElementById(el.name + '_chars_left').innerHTML = max_len - el.value.length;
return true;
}
var textarea = document.querySelector("#title textarea");
textarea.addEventListener("keyup", function() { change(this); });
document.querySelector("#reset-button").addEventListener("click", function() {
textarea.value = "";
change(textarea);
});
<h2 style="background-color: #eee; padding: 10px 20px 10px 20px; margin-
bottom: 20px;">Enter meta title tag</h2>
<form id="title">
<textarea style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2"></textarea>You've typed <span id="left_char_cnt"><b>0</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b>lots</b></span> more
<input class="btn btn-primary" type="button" id="reset-button" value="reset title" />
</form>
var t = document.getElementsByTagName('textarea')[0];
var a = document.getElementById('left_char_cnt');
var b = document.getElementById('left_chars_left')
t.addEventListener('keyup',function(){
var value = t.value.length;
var maxval = 60;
a.innerHTML = value
b.innerHTML = (maxval- value)
if(value == 60){ a.maxLength = maxval}
})
function resetVal(){
t.value = null;
a.innerHTML = '<b>0</b>'
b.innerHTML = '<b>lots</b>'
}
<h2 style="background-color: #eee; padding: 10px 20px 10px 20px; margin-
bottom: 20px;">Enter meta title tag</h2>
<form id="title">
<textarea style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2" maxlength="60"></textarea>You've typed <span id="left_char_cnt"><b>0</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b>lots</b></span> more
<input class="btn btn-primary" type="button" onclick='resetVal()' value="reset title"/>
</form>
Use this function, by replacing your 'myFunction()'
<script>
function myFunction() {
document.getElementById("title").reset(); // reset your form
document.getElementById("left_char_cnt").innerHTML = '<b>0</b>'; //reset your span counter
}
</script>

Javascript: Getting ASCII code of last character in textarea

In my javascript program I am trying to display ASCII code of last character of TextArea. For that I am getting value of textArea, getting last character of text area and using charCodeAt(139) to get the code of last character but it's not working. Can anyone tell me what's wrong in my code.
code:
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>signature</title>
<style>
#key{
color: #ffffff;
font-size: 20px;
text-align: center;
}
</style>
</head>
<body bgcolor="#3d382a">
<h2 style="color: #ffffff; text-align: center;"> MY MESSAGE </h2>
<form action="#" method="post">
<p style="text-align: center; color: #ffffff; font-size: 20px">
<textarea id="textarea" name="text" maxlength="140" rows="15" cols="40" ></textarea><br><br>
<span id="count"></span> characters</p><br>
<p id="key"> </p>
</form>
<script>
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) ;
var str = document.getElementById('textarea').value;
var lastChar = str.charAt(str.length - 1);
document.getElementById('key').innerHTML = "Last key in ASCII code: " + lastChar;
};
</script>
</body>
</html>
Change your last line. Right now you just are logging the last character, whilst you need to get the ASCII code.
document.getElementById('key').innerHTML = "Last key in ASCII code: " + lastChar.charCodeAt(0);
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) ;
var str = document.getElementById('textarea').value;
var lastChar = str.charAt(str.length - 1);
document.getElementById('key').innerHTML = "Last key in ASCII code: " + lastChar.charCodeAt(0);
};
<h2 style="color: #ffffff; text-align: center;"> MY MESSAGE </h2>
<form action="#" method="post">
<p style="text-align: center; color: #ffffff; font-size: 20px">
<textarea id="textarea" name="text" maxlength="140" rows="15" cols="40" ></textarea><br><br>
<span id="count"></span> characters</p><br>
<p id="key"> </p>
</form>
Move your last three lines into your onkeyup function, this will update the #key element every time the input is updated. You also want to use str.length - 1 in the charCodeAt function, as you want to get the code for the last character, not just the 140th.

Categories