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.
Related
I'm practicing JavaScript with the jQuery library.
What I want is to create something like a POS Application, but there are things I just can't figure out.
I'd like to, if you enter lays, and then you enter lays again, the output should change to the already appended output to lays * 2.
I'm kind of lost on how to achieve the desired.
What I have so far:
var billoutput = document.getElementById('inputterminal');
var counter = 1;
$('#bill').click(function() {
$("#holder").append(" <span style='padding:10px; margin:5px; color:white; background-color:black; border-radius: 10px;'> " + billoutput.value + " </span> ");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>POS Terminal</h1>
<input id="inputterminal" value="" name="" type="text">
<button id="bill">bill</button> <br>
<div style="margin-top: 20px;" id="holder"></div>
You can store the inputs in an array and check whether the array includes the value of the input every time the user clicks the button. If it does not, append the element and push the input's value to the array.
var billoutput = document.getElementById('inputterminal');
var counter = 1;
var words = []
$('#bill').click(function() {
if (!words.includes(billoutput.value)) {
words.push(billoutput.value)
$("#holder").append(" <span style='padding:10px; margin:5px; color:white; background-color:black; border-radius: 10px;'> " + billoutput.value + " </span> ");
}else{
alert("you already entered that!")
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>POS Terminal</h1>
<input id="inputterminal" value="" name="" type="text">
<button id="bill">bill</button> <br>
<div style="margin-top: 20px;" id="holder"></div>
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.
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
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>
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/