Count characters in textfield on keydown event - javascript

I want to live update the amount of characters entered in a textfield as the user puts them in. I am not getting too far. This is what I have so far. It changes to zero. I'm rather new to javascript to a beginner explanation would be great.
function doThis() {
x = document.getElementById("area").textContent;
y = x.length;
document.getElementById("demo").innerHTML = y;
}
<textarea id="area" onkeydown="doThis()"></textarea>
<p id="demo">Count goes here</p>

To get the content of the textarea use .value and change the event to onkeyup.
function doThis() {
x = document.getElementById("area").value;
y = x.length;
document.getElementById("demo").innerHTML = y;
}
<textarea id="area" onkeyup="doThis()"></textarea>
<p id="demo">Count goes here</p>

Alternative answer with .querySelector() and less code:
document.querySelector('#area').onkeyup = function() {
document.querySelector('#demo').innerHTML = this.value.length;
}
<textarea id="area"></textarea>
<p id="demo">Count goes here</p>

instead of textcontent use value and if you want to use keydown, add +1
function doThis() {
x = document.getElementById("area").value;
y = x.length + 1;
document.getElementById("demo").innerHTML = y;
}
<textarea id="area" onkeydown="doThis()"></textarea>
<p id="demo">Count goes here</p>
note: if you copy and paste it will give you wrong result, so better to use onkeyup

Related

Text input command aguments

How would I make commands for an input tag. For example, when you type !echo 'test' in an text input it would edit the content of a p tag
I tried this
<input type="text id="input" onchange="update()"/>
<p id="output"></p>
function update(){
var x = document.getElementById("input").value;
if(x == "!echo ", args){
document.getElementById("output").innerHTML = x;
}
}
If I understand the question correctly, you want to show the text that appears after the command "!echo". You're very close to getting it done. I've used the startWith method on the string of x to ensure the '!echo' command is at the beginning of the input. If that's true then we strip off the command using the replace method. I hope that's what you're looking for.
function update(){
var x = document.getElementById("input").value;
if (x.startsWith("!echo ")) {
document.getElementById("output").innerHTML = x.replace('!echo ', '');
}
}
<input type="text" id="input" onchange="update()"/>
<p id="output"></p>
Your question is unclear AMO.
Here's the result if you type !echo 'test' in your input tag.
If that's not the result your expect please update your question.
Feel free to add more details if it's not the goal you want.
I don't understand exactly what You want to do...
Have a nice day.
<input type="text" id="input" onKeyUp="update('\'test\'')">
<p id="output"></p>
function update(args){
var x = document.getElementById("input").value;
if(x == "!echo "+ args){
document.getElementById("output").innerHTML = x;
}else{
document.getElementById("output").innerHTML ="";
}
}

Issues outputting text via JavaScript

https://codepen.io/kev_daddy/pen/MMWEMG
I am building a form that is meant to update the difference between two values in real time (ie without refreshing the page). It is comprised of multiple fields, but ultimately I'll be getting the sum of two values, and displaying this using HTML.
The entire thing appears to work as intended until I get to the function that is meant to display the sum in html.
The intention is that the result (a hidden field) is shown as plain text in output. It doesn't trigger on the onset, however if i punch in an extra character using my keyboard, the event is finally heard and the text shows. up.
I am sure that I am missing something, but how do I ensure that the sum is outputted?
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult; }
var input = document.getElementById("result");
var output = document.getElementById("output"); input.addEventListener("input", function() {
output.innerText = this.value;
});
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!
There is no input event on span. You can create a separate function and pass the value of the calculation to this function whose responsibility will be to update the span text content
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult;
updateText(myResult)
}
function updateText(val) {
document.getElementById("output").innerText = val;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!

How can I remove spaces, punctuation and symbol from my text

I am building an app whereby I have to make some conversions to an input string. I need to remove whitespaces, punctuation and make everything down-cased. I do not get any output when I try to test it.
Further, I need to ensure that more than one word is entered and at Least 60 characters in the input box.
const text = document.querySelector('#normalized_text');
const string = document.querySelector('#message');
function encodeMessage() {
let newMessage = string.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
console.log(newMessage);
text.innerHTML = newMessage;
return newMessage;
}
<form>
<input type="text" placeholder="Type your secret message" id="message">
</form>
<button type="submit" class="button" onclick="encodeMessage()">Encode message</button>
<div class="box">
<h3>Normalised Text</h3>
<p id="normalized_text"></p>
</div>
Currently, you're not replacing the value of the object 'string' but rather just the object. If you check your developer console, you will find an error message. I recommend using the developer console (by going to Inspect Element) as much as possible when creating a webpage because it can show the errors in your script.
You should change your JavaScript code to the following:
const text = document.querySelector('#normalized_text');
const string = document.querySelector('#message');
function encodeMessage() {
let newMessage = string.value.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
text.innerHTML = newMessage;
return newMessage;
}
A few issues here:
1- As pointed out by #epascarello, your button is of type submit, which by default refreshes the page. We do not want that in the case, so simply make your button to be of the type button.
2- You are trying to manipulate the object string, not its value! try working with string.value instead.
Regarding the word count checking, you can split the string by the space character and check the resulting array's length.
const text = document.querySelector('#normalized_text');
const str = document.querySelector('#message');
function encodeMessage() {
var message = str.value;
if(getWordCount(message) < 2 || message.length < 60) {
console.log("Invalid message.");
return null;
}
let newMessage = str.value.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
console.log(newMessage);
text.innerHTML = newMessage;
return newMessage;
}
//gets word count of a string
function getWordCount(s) {
return s.split(" ").length;
}
<form>
<input type="text" placeholder="Type your secret message" id="message">
</form>
<button type="button" class="button" onclick="encodeMessage()">Encode message</button>
<div class="box">
<h3>Normalised Text</h3>
<p id="normalized_text"></p>
</div>

HTML button with different output onclick using JavaScript

I have the following setup - http://codepen.io/anon/pen/WvjmLv?editors=100 and am trying to output text depending on which button is clicked
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="right-answer" type="button">6</button>
<button class="wrong-answer" type="button">10</button>
<script>
var text;
var wrongAnswer = document.getElementsByClassName("wrongAnswer").addEventListener("click");
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click");
if (wrongAnswer) {
text = "Incorrect!";
text = "Wrong!";
text = "Try Again!";
}
if (rightAnswer) {
text = "Correct!";
}
document.getElementById("answer").innerHTML = text;
</script>
</div>
<div>
<p id="answer"></p>
</div>
If the user selects the wrong answer, it should either read Wrong!, Incorrect! or Try Again! (without repeating the same text output if their next guess is also wrong)
If they get the answer right, it should just simply read Correct!
As I'm fairly new to JavaScript, I feel as though I'm a little bit off with my solution and was wanting to know how can I make this function work?
Thanks.
Easiest and fastest way to get the result you want is by adding onclick-eventhandlers to your buttons.
<button onclick="somefunction()"></button>
After that you can easily handle what should happen after that click.
In your case I would check what's in the class attribute of the button you clicked.
By doing this you can print the results to your #answer-container.
With a simple array and a global variable of which index is next you can output different "false"-messages.
var _i = 0;
var _wrongs = ['Incorrect!', 'Wrong!', 'Try Again!'];
function showResult(b) {
var res = document.getElementById('answer');
if (b.classList.contains('right-answer')) {
res.innerHTML = 'Correct'
} else {
res.innerHTML = _wrongs[_i];
_i = _i > 1 ? 0 : _i + 1;
}
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" onclick="showResult(this)">2</button>
<button class="wrongAnswer" onclick="showResult(this)">5</button>
<button class="right-answer" onclick="showResult(this)">6</button>
<button class="wrong-answer" onclick="showResult(this)">10</button>
</div>
<div>
<p id="answer"></p>
</div>
Demo on Codepen
Well, there are a couple things that you need to do:
You do not have a separate click handler function defined.
You need to properly add the event function to the addEventListener call.
You cannot attach an event to multiple elements at once. You need to loop over them.
Why do you have two different classes? i.e. 'wrongAnswer' and 'wrong-answer'? Please make sure that you stick with one convention.
I added an onReady() to wait for the DOM to load before accessing and adding listeners to the elements.
Addition Information
Below, I have wrapped the document.getElementsByClassName(className) call with [].slice.call(scope, [begin[, end]]) because the result of getElementsByClassName is a NodeList. You cannot treat a list like an array in JavaScript. Since I used Array.prototype.forEach to loop over the elements, they needed to transformed into an array. This is simply syntactic sugar in order to make the code look more aesthetically pleasing and readable.
This could have easily been accomplished with a for-loop:
var nodes = document.getElementsByClassName("rightAnswer");
for (var i = 0; i < nodes.length; i++) {
var el = nodes[i];
el.addEventListener('click', clickHandler);
}
Code
var wrongTextArr = ['Try Again!', 'Wrong!', 'Incorrect!'];
var guesses = 0;
onReady(function() {
// Set the number of guesses equal to the number of questions - 1.
guesses = document.querySelectorAll('.question button').length - 1;
[].slice.call(document.getElementsByClassName('wrongAnswer')).forEach(function(el) {
el.addEventListener('click', clickHandler);
});
[].slice.call(document.getElementsByClassName('rightAnswer')).forEach(function(el) {
el.addEventListener('click', clickHandler);
});
});
function clickHandler(e) {
var text = '';
var target = e.target;
var targetClass = target.className;
if (guesses < 1) {
text = 'You have reached the max number of attempts!';
} else if (targetClass === 'wrongAnswer') {
text = wrongTextArr[--guesses]; // Decrement guesses.
} else if (targetClass === 'rightAnswer') {
text = 'Correct!';
} else {
text = 'Unexpected Error!';
}
document.getElementById('answer').innerHTML = text;
}
function onReady(callback) {
var intervalID = window.setInterval(function() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}, 1000);
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
In the code above, I tried not to stray too far away from your original code, I just simply pointed out things that made your code not work and fix them with the minimalist amount of effort. Here is my solution that I would go with.
var wrongTextArr = ['Try Again!', 'Wrong!', 'Incorrect!'];
var guesses = 0;
onReady(function() {
// Set the number of guesses equal to the number of questions - 1.
guesses = document.querySelectorAll('.question button').length - 1;
addEventListeners('button[class$="Answer"]', 'click', function(e) {
document.getElementById('answer').innerHTML = getText(e.target.className.split());
});
});
function getText(classList) {
if (guesses < 1) {
return 'You have reached the max number of attempts!';
} else if (classList.indexOf('wrongAnswer') > -1) {
return wrongTextArr[--guesses]; // Decrement guesses.
} else if (classList.indexOf('rightAnswer') > -1) {
return 'Correct!';
} else {
return 'Unexpected Error!';
}
}
// Generic functions.
function addEventListeners(selector, event, listenerFn) {
[].slice.call(document.querySelectorAll(selector)).forEach(function(el) {
el.addEventListener(event, listenerFn);
});
}
function onReady(callback) {
var intervalID = window.setInterval(function() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}, 1000);
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
Lots of good answers.. Here is another approach,
HTML:
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">2</button>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">5</button>
<button class="rightAnswer" type="button" onclick="checkAnswer(this)">6</button>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">10</button>
</div>
<div>
<p id="answer"></p>
</div>
JS:
<script>
var count = 0;
var wrongtext = ["Incorrect!", "Wrong!", "Try Again!"];
function checkAnswer(el) {
if (el.classList.contains('wrongAnswer')) {
count++;
if(count === 3)
count = 0;
alert(wrongtext[count])
}
if (el.classList.contains('rightAnswer')) {
alert('correct');
}
}
</script>
Demo:
https://jsfiddle.net/cubq361t/22/
I am not totally sure how to make it so it will say different things like "wrong" and "incorrect" but I hope this will point you in the right direction:
<!DOCTYPE html>
<html lang="en">
<body>
<div class="section">
<p>How many sides does a hexagon have?</p>
<input type="button" onClick="wrongAnswer()" value="2">
<input type="button" onClick="wrongAnswer()" value="5">
<input type="button" onClick="rightAnswer()" value="6">
<input type="button" onClick="wrongAnswer()" value="10">
<p id="text"></p>
</div>
<script>
function wrongAnswer() {
document.getElementById('text').innerHTML = "Wrong";
}
function rightAnswer() {
document.getElementById('text').innerHTML = "Correct!";
}
</script>
</body>
</html>
Here is an updated version of your code. The main issue you had was mixing up your variable and function names.
Here is a
Fiddle
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
<script>
var text;
var wrongAnswers = document.getElementsByClassName("wrongAnswer");
var rightAnswers = document.getElementsByClassName("rightAnswer");
for (var i = 0; i < wrongAnswers.length; i++) {
// alert( wrongAnswers[i]);
wrongAnswers[i].addEventListener('click', printWrongAnswer);
}
for (var i = 0; i < rightAnswers.length; i++) {
rightAnswers[i].addEventListener('click', printRightAnswer);
}
function printRightAnswer() {
text = "Correct!";
printAnswer();
};
function printWrongAnswer() {
text = "Incorrect!";
text += "Wrong!";
text += "Try Again!";
printAnswer();
}
function printAnswer() {
document.getElementById("answer").innerHTML = text;
}
</script>
In addition to the answers of Mr. Polywhirl and Bellash:
If you are new to JavaScript you should try to understand how the EventBindings are working. Every binding in JavaScript is an event, so if you click somewhere the Browser will check if he will find a binding which is listening to the event "click". So its irrelevant when you bind the event but it has to be before the click. However you have to tell JavaScript which function he has to call if someone clicks your button! Thats because events are kinda "floating" in you browser scope, they are present but know one knows when they are actually be triggered but if they are getting triggered the script have to know what gets triggered or in other words: which functionality should be triggered now?
Your lines
var wrongAnswer = document.getElementsByClassName("wrongAnswer").addEventListener("click");
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click");
are wrong because you never told the event "click" what functionality should be executed if the button is clicked.
The call or one type of a correct call would be:
var someFunction = function() { // DO YOUR AWESOME WORK PLS! }
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click", someFunction);
and in addition to that:
I don't know how experienced you are in programming but this lines
text = "Incorrect!";
text = "Wrong!";
text = "Try Again!";
will override each other, because you are using the same variable in all 3 rows ;)
Mr. Polywhirl and Bellash posted you some good example to begin with. Try them out and try to understand them!
Hope this makes it a bit clearer!
cheers,
Sebastian
Here's a rewrite of your code, providing comments as a sort of tutorial:
Update: added random response generation.
HTML:
<div class="question">
<p>How many sides does a hexagon have?</p>
<!--
Use a common class ('answer-button' used here) for all buttons
so that clicks can be easily handled with a single listener.
Since you know any answers that aren't right are wrong, you can
simply add a 'right-answer' class for that one and leave the
others as is.
-->
<button class="answer-button" type="button">2</button>
<button class="answer-button" type="button">5</button>
<button class="answer-button right-answer" type="button">6</button>
<button class="answer-button" type="button">10</button>
</div>
<div>
<!--
Using an id is often unnecessary, so I'd switch this to a class.
Since the above buttons represent answers, using an "answer" class
on this paragraph can bring confusion, so I'd recommend using something
more accurate, such as "response".
-->
<p class="response"></p>
</div>
<!--
Generally you'll want your js in a separate file. If you include the script, whether
inline or separate, at the bottom of the body element, as you did initially, it will
automatically execute after the dom has initialized, which is good.
-->
JavaScript:
// Wrap in an immediately invoking function expression
// to keep your variables off the global scope.
(function() {
// Capture all of your response phrases in an object.
var responses = {
correct: [
"Correct!"
],
incorrect: [
"Wrong!",
"Try Again!",
"Incorrect!"
]
};
// Get the element that will display your answer.
// getElementsByClassName returns an array, so get the
// first element in the array.
var response = document.getElementsByClassName('response')[0];
// Get all of the answer buttons.
var answerButtons = document.getElementsByClassName('answer-button');
// Set a listener on each answerButton element.
for (var i = 0; i < answerButtons.length; i++) {
// Add the event listener to the element. When the event occurs,
// the checkAnswer function will run, and will be passed an event object.
answerButtons[i].addEventListener('click', checkAnswer);
}
// event is an object that is automatically passed in
// when the listener calls this function, and event.target
// is the element where the event occurred.
function checkAnswer(event) {
// initialize a variable for the message
var message;
// get the element where the event occurred
var element = event.target;
// get all classes from target element
var classes = event.target.className;
// classes will be in a space-separated string, so
// we convert that to an array
classes = classes.split(' ');
// check if a specific class is in the array
if (classes.indexOf('right-answer') >= 0) {
// if the 'right-answer' class is there, they
// clicked the right answer.
message = getRandomArrayElement(responses.correct);
} else {
// otherwise, they clicked the wrong answer
message = getRandomArrayElement(responses.incorrect);
}
// set the target element's content to the message
response.textContent = message;
}
function getRandomArrayElement(array) {
// This function picks a random element from an array and
// returns it.
// You're going to want to pick one of these array items by their
// index, so we'll set up variables to capture the lowest and
// highest possible numbers that can be used.
var min = 0;
var max = array.length - 1;
// Javascript provides random numbers using the Math.random function,
// wich gives a random float between 0 and 1. The expression below
// uses that to generate a random number within a given range - in this
// case, between min and max.
var index = Math.floor(Math.random() * (max - min + 1)) + min;
return array[index];
}
})();
I have edited your code to help you understand how you could deal with .getElementsByClassName
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="rightAnswer" type="button">10</button>
</div>
<div>
<p id="answer">ok</p>
</div>
<script>
var text="...",
wrongs=document.getElementsByClassName("wrongAnswer"),
rights=document.getElementsByClassName("rightAnswer"),
wrongTexts=["Incorrect","Try Again","Wrong!"],
i=0;
for(var i=0; i< wrongs.length; i++){
wrongs[i].addEventListener("click",function(e){
text = "Incorrect!";
DisplayText();
});
}
for(var i=0; i< rights.length; i++){
rights[i].addEventListener("click",function(e){
text = "Correct!";
DisplayText();
});
}
function DisplayText(){
i=i%wrongTexts.length;
text=text=="Correct"?text:wrongTexts[i++];
document.getElementById("answer").innerHTML = text;
}
</script>
Make a function first and the assign it to the buttons like
<button onclick="myFunction()">Click me</button>
<p class="demo"></p>
Then in the JS
function myFunction() {
document.getElementByClassName("demo").innerHTML = "Hello World";
}
in your pen make a function add all the logic in it and call it on button click

How can i modify a input number field by click of a button in javascript?

i am trying to increase the value in input text field when a button is clicked but to be honest i dont know correct way since i am a newbie to javascript. i have done this much.
function input1()
{
var x = document.getElementById("box").value;
document.getElementById("box").innnerHTML= x*10+1 ;
}
but its not working.
here is the html of the input field.
<input type="number" name="display" id="box"style="height:55px;font-size:25px;text-align:end;">
function input1()
{
var x = +document.getElementById("box").value;
document.getElementById("box").value= x*10+1 ;
}
Input tags do not have innerHTML; use the value property if you want to reassign text in an input.
function input1()
{
var x = document.getElementById("box").value;
document.getElementById("box").value = x * 10 + 1;
}
You have to set the value with
document.getElementById("box").value = x*10+1 ;
You can try this:
function input1() {
var box = document.getElementById("box");
box.value = box.value * 10 + 1;
}
Also, I added "value=0" to your HTML:
<input type="number" name="display" id="box" value="0" style="height:55px;font-size:25px;text-align:end;">
https://jsfiddle.net/lemoncurry/xxyjoLa7/1/

Categories