I am working on a small word counter for a school assessment and can't see what is wrong with this code. The idea is when you hit the submit button, it displays "Word Count: " and the amount of character put into a text box. I have showed the teacher my code and he agrees that he doesn't see a problem with it.
Javascript:
window.onload = function(){
var input = document.getElementById(userInput).value;
if(submit.onclick) {
document.getElementById("wordCount").innerHTML = "Word Count: " + input.length;
};
};
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
document.querySelector('#submit').addEventListener('click', function(e) {
const input = document.querySelector('#userInput');
const inputValue = input.value;
const wordsArray = inputValue.split(' ');
document.querySelector('#wordCount').innerText = `Word Count: ${wordsArray.length}`;
})
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
First on window load there is likely no information inside the #userInput, meaning
var input = document.getElementById(userInput).value; will be undefined or ''.
Second, you have no click event bound to your submit button so
submit.onclick will return false;
Binding DOM events
Lastly I switched from using .innerHTML to .innerText as there is no HTML being added into it. Also you your original code was not getting the word count, but would have returned the character count of the input text. To get word count I split the input text on spaces and returned the length of that array as the word count.
Try putting quotes around your userInput inside your getElementById. Right now you're trying to get an element by an ID of undefined because the userInput variable doesn't exist.
Related
How do I use a checkbox in JS/jQuery to toggle just between 2 numbers?
I want unchecked to always be $0 and checked to always be $100. The code below comes close. I'm looking to use str.replace as opposed to switching divs using display:none.
Code:
function myFunction() {
let str = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = str.replace("$0", "$100");
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String</h2>
<p>The replace() method searches a string for a specified value, or a regular expression,
and returns a new string where the specified values are replaced.</p>
<p id="demo">$0</p>
<input type="checkbox" onclick="myFunction()" value="Try It">
</body>
</html>
function myFunction() {
const element = document.getElementById('demo')
element.innerText = element.innerText === '$0' ? '$100' : '$0'
}
I have found several questions with answers on how to do this, but I think my problem is an interesting one. I am trying to have a user enter in their name in a text box, then once they hit a button it will display it back to them.
This is the code I have:
<html>
<head>
<title>Side Bar test</title>
<link rel="stylesheet" href="test.css" />
</head>
<body>
<div id="sideWrapper">
<p id="wrapper"><label for="name">Name: <input type="text" name="name" id="name"></p>
<button onclick="display();">Submit</button>
</br>
<div id="playerName">
</div>
</div>
</body>
<script type="text/javascript" language="javascript">
var input = document.getElementById("name").value;
function display() {
document.getElementById("playerName").innerHTML = "<p>Player: " + input + "</p>";
}
</script>
When the document.getElementById("name").value is called, it only takes whatever was in the text field when the page first loaded. Trying to update it after and clicking the button doesn't work. So, if you type "John Doe" in the field and then reload the page and hit the button, it will display John Doe. But if you try to change it, it doesn't work. I have tried moving the script to the <head> but that only makes it undefined.
How can I make it so the display() function sees what the user types in the box and updates it to print it out to the screen?
EDIT: Fixed the code by moving the input line into the function body.
<script type="text/javascript" language="javascript">
function display() {
var input = document.getElementById("name").value;
document.getElementById("PlayerName").innerHTML = "<p>Player: " + input + "</p>";
}
</script>
You need to put your declaration of input inside your display function.
function display() {
var input = document.getElementById("name").value;
document.getElementById("playerName").innerHTML = "<p>Player: " + input + "</p>";
}
As you currently have it, the value of input is stored when the page is loaded, so it does not update automatically.
You're problem is that this: var input = document.getElementById("name").value;
fires immediately when the program loads.
To fix this, do this:
function display() {
var input = document.getElementById("name").value;
document.getElementById("playerName").innerHTML = "<p>Player: " + input + "</p>";
}
That way, the input variable is assigned the current value of the input element each time the function is called.
Here is a fiddle to show that the input variable assignment fires when the page is loading. I added a default value to the input to show that no matter what you change it to afterwards, the value is always what the default is.
The input = document.getElementById("name").value; should be inside the function display(), because you will always set it it's initial value (empty).
Now this is just for reference for a future project but I am trying to call a function that reads in a string but displays a float after. So I first check the string then display a random number. The problem I am having, I think, is with the document.getElementById part. Any suggestions??
HTML File:
<html>
<body>
<input type="text" id="letter" value=""/><br/>
<input type="button" value="LETS DO THIS!" onclick="floatNum();"/></br>
<script type="text/javascript" src="letNum.js"></script>
</body>
</html>
External JS File:
function floatNum()
{
var val1 = document.getElementById("letter");
if (isNaN(val1)
{
alert(Math.random())
}
}
the following code is working:-
in your code,you missed closing parenthesis ")" near to "if condition"
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>demo</title>
<script type="text/javascript">
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value))// using input fields value not the whole object
{
alert(Math.random());
}
}
</script>
</head>
<body>
<input type="text" id="letter" value="" /><br />
<input type="button" value="LETS DO THIS!" onclick="floatNum();" />
</body>
</html>
Yes, you want to pass in the element in the function, like so:
<input type="button" value="LETS DO THIS!" onclick="floatNum(document.getElementById('letter'))"/></br>
And in your JS
function floatNum(el)
{
if (isNaN(el)
{
alert(Math.random())
}
}
In case of a reusable function - try not to make it dependent on your DOM. Think about what would happen if you rename your element or want to use this function again. You couldn't before - now you can.
The problem is on this line:
var val1 = document.getElementById("letter");
It should be:
var val1 = document.getElementById("letter").value;
The first sets val1 to the DOM element representing the input tag, the second sets it to the text value of the input tag (its contents).
You need to process the value of input field not the input field itself.
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value) // using input fields value not the whole object
{
alert(Math.random())
}
}
You don't grab the value of the input, but the input itself.
Correct code would be :
var val1 = document.getElementById("letter").value;
I use the following code.
The idea is to print the contents of the div with name "PrintThis" which incorporates the text input area "textarea1".
The problem is that getElementById only ever returns the string loaded with the page; "cake" in this case.
If I change "cake" to "pie" by clicking and typing into "textarea1" on the page then printContents still has "cake" not "pie".
<html>
<head> </head>
<script type="text/javascript">
function printFunction(divName) {
var printContents = document.getElementById(divName).innerHTML;
//Now call a script to print (not included)
}
</script>
<body>
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10" style="width:95%!important;" ">cake</textarea>
</div>
<input type="button" value="Print Div" onClick="printFunction('printThis')">
</body></html>
In my production version I also use AJAX to post the text area value back to the server, so could in theory use a page refresh, though that doesn't run, I tried using these options.
document.location.reload(true);
window.top.location=window.top.location;
The production version does have jQuery available too.
first of all you are trying to get innerHTML of the div, instead of the actual textarea.
secondly instead of trying to get innerHTML try using value.
http://jsfiddle.net/qdymvjz8/
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10">cake</textarea>
</div>
<input type="button" value="PrintDiv" onClick="printFunction('textarea1')">
function printFunction(divName) {
var printContents = document.getElementById(divName).value;
}
If you are having multiple items in your div in production then you can iterate through the children of the div and drag out the values.
function printFunction(divName) {
var printContents = document.getElementById(divName),
childItemCount = 0,
stringToPrint = '';
for (childItemCount; childItemCount < printContents.children.length; childItemCount++) {
stringToPrint += printContents.children[childItemCount].value;
}
console.log(stringToPrint);
//Now call a script to print (not included)
}
I'm doing some very rudimentary javascript work and seem to hit a bump. For the life of me, I can't seem to find what should be a very basic answer on Google.
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function lowerCase(){
var input = document.send.inputText;
input.toLowerCase();
document.write(input);
alert(input);
}
</script>
</head>
<body>
<h1>Test Page</h1>
<form name="send">
<input type='text' name="inputText" onkeypress="lowerCase()"/>
</form>
</body>
</html>
My intent is that the function lowerCase is executed on entering information into the textbox and pressing enter. However, I can never seem to get the function to execute.
How about...
HTML:
<input type='text' name="inputText" onkeypress="lowerCase(this)">
JavaScript:
function lowerCase ( input ) {
setTimeout( function () {
input.value = input.value.toLowerCase();
}, 0 );
}
Live demo: http://jsfiddle.net/vXpj8/3/
function lowerCase ( e ) {
if ( e.keyCode === 13 ) {
this.value = this.value.toLowerCase();
e.preventDefault();
}
}
document.send.inputText.onkeypress = lowerCase;
Live demo: http://jsfiddle.net/vXpj8/1/
Notice, how I bind the event handler with JavaScript. I do this because I want to have the event object available in the function.
There's a space between the onkeypress attribute and equals sign. Remove that; it should work.
Fiddle: http://jsfiddle.net/iambriansreed/jEnxH/
<form name="send">
<input type='text' name="inputText">
</form>
<script>
document.send.inputText.onkeypress = function(event){
if(event.keyCode != 13) return;
this.value = this.value.toLowerCase();
alert(this.value.toLowerCase());
event.preventDefault();
};
</script>
If you want it to work when the enter key is pressed, then you'll need to deal with the form being submitted, since pressing enter in a text input element that is a form control submits the form.
More likely you want to change the value to lower case on some other event, such as keup, e.g.
<input onkeyup="this.value = this.value.toLowerCase();" ... >
Doing this sort of thing is a bit annoying for users though, since upper case letters are magically changed to lower case. If there is a back-end requirement for lower case letters, better to deal with it there than confuse users entering text.
a few issues with your code
first var input is a input box not the string, toLowerCase() is a string method, you need input value
var input = document.send.inputText;
alert(input.value);
second, onkeypress is excuted before text is entered, maybe you should consider change onkeypress to onkeyup
try if this helps
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function lowerCase(){
var input = document.send.inputText;
input.value = input.value.toLowerCase();
}
</script>
</head>
<body>
<h1>Test Page</h1>
<form name="send">
<input type='text' name="inputText" onkeyup="lowerCase()">
</form>
</body>
</html>