Getting two javascripts working on the same page - javascript

I found a script along with some HTML that counts the amount of characters you type into a box:
<script type="text/javascript">
function change (el) {
var max_len = 50;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
}
document.getElementById('char_cnt').innerHTML = el.value.length;
document.getElementById('chars_left').innerHTML = max_len - el.value.length;
return true;
}
</script>`
<form>
<textarea style="border: 1px solid #eb008b;" cols=100 rows=2
onkeyup="change(this);"></textarea>
<p>You've typed <span id="char_cnt">0</span> character(s)</p>
<p>You are allowed <span id="chars_left">lots</span> more</p>
</form>
In this example, it counts up to 50 characters.
I want to add a second form on the same page that counts up to 200 characters. When I duplicate the code it stops one script working.
How do I add it so both scripts work on the same page?

Why exactly are you setting up a second JS function?
You could easily determine which form is getting worked in when you trigger them by id or name attribute.
Try something like this:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function change (el) {
if (el.value.length > el.maxLength) {
el.value = el.value.substr(0, el.maxLength);
}
document.getElementById(el.name + '_char_cnt').innerHTML = el.value.length;
document.getElementById(el.name + '_chars_left').innerHTML = el.maxLength - el.value.length;
return true;
}
</script>
<form>
<!-- Left Textarea -->
<textarea name="left" style="border: 1px solid #eb008b;" cols=100 rows=2 maxLength=50 onkeyup="change(this);"></textarea>
<p>You've typed <span id="left_char_cnt">0</span> character(s)</p>
<p>You are allowed <span id="left_chars_left">lots</span> more</p>
<!-- Right Textarea -->
<textarea name="right" style="border: 1px solid #eb008b;" cols=100 rows=2 maxLength=200 onkeyup="change(this);"></textarea>
<p>You've typed <span id="right_char_cnt">0</span> character(s)</p>
<p>You are allowed <span id="right_chars_left">lots</span> more</p>
</form>
</body>
</html>

You are probably duplicating id attributes when you copy your form code. document.getElementById() will only get the first instance of something with the id specified.
Try something like this instead:
const MAX_LEN = 50;
Array.from(document.querySelectorAll("form")).forEach(form => {
const ta = form.querySelector("textarea"),
cc = form.querySelector("span.char_count"),
cl = form.querySelector("span.chars_left");
ta.addEventListener("keydown", () => {
if (ta.value.length > MAX_LEN) {
ta.value = ta.value.substr(0, MAX_LEN);
}
cc.innerHTML = ta.value.length;
cl.innerHTML = MAX_LEN - ta.value.length;
});
});
<form>
<textarea style="border: 1px solid #eb008b;" cols=100 rows=2></textarea>
<p>You've typed <span class="char_count">0</span> character(s)</p>
<p>You are allowed <span class="chars_left">lots</span> more</p>
</form>
<form>
<textarea style="border: 1px solid #eb008b;" cols=100 rows=2></textarea>
<p>You've typed <span class="char_count">0</span> character(s)</p>
<p>You are allowed <span class="chars_left">lots</span> more</p>
</form>

Related

HTML submit button to create a paragraph element inside a div and appent form value to the paragraph

I need a javascript function that can be used to get the value of an HTML form, create a paragraph inside a div container and input the form value into the created paragraph whenever the submit button is clicked. The javascript code i tried seems not to be responding well.
Note: I don''t want the form to return any value.
Here's the whole HTML and javascript code, the button kept on submitting the form value to the page and not updating the commentBox container.
<div class="chat-popup" id="myForm">
<form name="commentForm" class="form-container">
<label for="msg"><b>Comment</b></label>
<textarea id="myComment" placeholder="Type comment.." name="msg" required></textarea>
<button type="submit" class="lk-btn" onclick="postComment(); return false">Send</button>
<button class="lk-btn" onclick="closeForm()">Close</button>
</form>
</div>
</div>
<div id="commentBox" style="width: 400px; height: 400px; background-color: white; color: green;"></div>
function postComment() {
var paragraph = document.createElement("p");
p.id = 'com';
document.getElementById('com').innerHTML = document.getElementById('myComment').value;
var commentContainer = document.getElementById('commentBox');
commentContainer.appendChild(paragraph);
return false;
}
Just ommit the whole "id" thing and it's done:
function postComment() {
var paragraph = document.createElement("p");
paragraph.innerHTML = document.getElementById('myComment').value;
var commentContainer = document.getElementById('commentBox');
commentContainer.appendChild(paragraph);
return false;
}
<div class="chat-popup" id="myForm">
<form name="commentForm" class="form-container">
<label for="msg"><b>Comment</b></label>
<textarea id="myComment" placeholder="Type comment.." name="msg" required></textarea>
<button type="submit" class="lk-btn" onclick="postComment(); return false">Send</button>
<button class="lk-btn" onclick="closeForm()">Close</button>
</form>
</div>
</div>
<div id="commentBox" style="width: 400px; height: 400px; background-color: white; color: green;"></div>
The created p element reference is stored in variable paragraph. In order to assign id attribute use paragraph.id instead of p.id.
Since the newly created p is not yet appended to the document. So, the statement document.getElementById('com') will return null.
document.querySelector('button')
.addEventListener('click', function() {
const p = document.createElement('p');
p.id = "com";
const val = document.getElementById('myComment').value;
if (val.length) {
p.innerHTML = val;
document.querySelector('div').appendChild(p);
}
});
<input type="text" id="myComment">
<div></div>
<button>Click Me</button>
--Edit--
function postComment(e) {
e.preventDefault();
const p = document.createElement('p');
p.id = "com";
const val = document.getElementById('myComment').value;
if (val) {
p.innerHTML = val;
document.getElementById('commentBox').appendChild(p);
}
}
<div class="chat-popup" id="myForm">
<form name="commentForm" class="form-container">
<label for="msg"><b>Comment</b></label>
<textarea id="myComment" placeholder="Type comment.." name="msg" required></textarea>
<button type="submit" class="lk-btn" onclick="postComment(event); return false">Send</button>
<button class="lk-btn" onclick="closeForm()">Close</button>
</form>
</div>
<div id="commentBox" style="width: 400px; height: 400px; background-color: white; color: green;"></div>
I finally did this more easily using p5.js library.
Simply Calling function CreateP() did the trick.

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.

When text is entered correctly, image lights up/changes

I am building a section on my website for language learning. The user will see the word でんき (Japanese word). When someone enters in the correct text that matches each symbol, one of them will light up. How could I achieve this?
Here is a preview image of my site: http://imageshack.us/photo/my-images/827/hiraganaquiz2.jpg/
Here's an example with a normal input field:
<script type="text/javascript">
var answer = 'foo';
function checkMatch(val) {
if (val == answer) {
alert('CORRECT!');
}
}
</script>
<input type="text" id="word_box" value="" onkeyup="checkMatch(this.value)" />
This is incredibly simplified, but you get the idea. onkeyup will be called whenever a key is pressed in a box or other editable field.
Here's another one to add to the mix. Short answer is use Javascript, HTML, and CSS to accomplish this.
http://jsfiddle.net/BUxvx/1/
HTML
<span data-answer="cat" data-for="1">Symbol 1</span>
<span data-answer="dog" data-for="2">Symbol 2</span>
<span data-answer="chicken" data-for="3">Symbol 3</span>
<br />
<input type="text" data-for="1" />
<input type="text" data-for="2" />
<input type="text" data-for="3" />
< - Type answers here
<br />
<span>cat</span>
<span>dog</span>
<span>chicken</span>​
JavaScript
$('input').keyup(function(){
$txt = $(this);
$span = $('span[data-for="' + $txt.attr('data-for') + '"]');
if($(this).val() === $span.attr('data-answer')){
$span.addClass('highlight');
}else{
$span.removeClass('highlight');
}
}); ​
CSS
span{
display:inline-block;
height:75px;
width:75px;
line-height:75px;
text-align:center;
border:1px solid black;
}
input{
width:75px;
border:1px solid black;
}
.highlight{
background-color:yellow;
}
​
HTML
<div class="question">
<span data-answer="correctAnswerOne">で</span>
<span data-answer="correctAnswerTwo">ん</span>
<span data-answer="correctAnswerThree">き</span>
<div>
<label for="answer">Enter your Answer</label>
<input id="answer" />
Javascript
//Build an array of correct answers
var answerArray = "";
var i = 0;
$('.question span').each( function() {
answerArray[i] = this.attr('data-answer');
i++;
} );
//On key up, get user input
$('input').keyup(function(){
$('.question span').removeClass('highlight');
var userInput = $('#inputElementID');
var userInputArray = string.split(' ');//Split the string into an array based on spaces (I assume you are looking for three separate words
var answerCount = array.length;
for (i=0;answerCount >= i;i=i+1) {
if (userInputArray[i] == answerArray[i]) {
$('span[data-answer=' + answerArray[i] + ']').addClass('highlight');
}
}
});
CSS
.highlight{
background-color:yellow;
}
Here's a simple way:
<span data-value="Car">{character that means Car}</span>
<span data-value="Boat">{character that means Boat}</span>
<span data-value="Plane">{character that means Plane}</span>
<input>
$('input').keyup(function(){
var val = $(this).val();
$('[data-value]').removeClass('highlight');
$('[data-value="'+val+'"]').addClass('highlight');
});
Explanation:
The data-value will hold the English text of your character. When the user types a value that matches it, it will add the highlight class to all elements that have a data-value matching the text. Just apply your "lighting up" styles to the class.
Demo: http://jsfiddle.net/MTVtM/
To work with multiple words just split the value by a space and check each piece:
$('input').keyup(function(){
var val = $(this).val();
$('[data-value]').removeClass('highlight');
val.split(' ').forEach(function(v) {
$('[data-value="'+v+'"]').addClass('highlight');
});
});
Demo: http://jsfiddle.net/MTVtM/1/ (Try entering "Car Boat")

Categories