Count down from user entered number in HTML and Javascript - javascript

So i have an input box that a user can enter a number into and upon clicking Commit, that number displays in a tag.
I then want this number to start counting down when I click Start.
I am new to Javascript and this is essentially a little project to help me learn, maybe I've thrown myself in too far, but I'm too invested now and would appreciate any help.
My HTML:
<span style="font-size: 36pt; font-family: homiziothin; color: black; padding-right: 20px;">£</span>
<input id="inputvalue" type="number" name="Value" min="0" max="500">
<button id="commitprice" type="submit" onclick="submitPrice()">Commit Price</button>
<p id="submittedprice"></p>
<button id="startauction" type="submit" onclick="startAuction()">Start Auction</button>
and my current Javascript to get the user value into the tag (and a rough guess going from multiple searches on google of how to start the countdown)
<script type="text/javascript">
function submitPrice()
{
var $pricesubmitted = $("#inputvalue").val();
$("#submittedprice").text($pricesubmitted);
}
function startAuction()
{
debugger;
var $startingprice = $("#inputvalue").val();
var $bidcountdown = setInterval(function()
{
$startingprice--;
document.getElementById("#inputvalue").textContent = $startingprice;
if($startingprice <= 0)
clearInterval($bidcountdown);
}, 1000);
}
</script>
At the moment it's erroring and saying that textContent can't be NULL.
Also just to point out the Actual populating of the P tag is working, its the countdown that isn't.

textContent property represents the text between opening and closing tags of an element. With your input, you need value property, because you don't have any text between those tags.
More info: How do I get the value of text input field using JavaScript?

I have implemented your requirement in a fiddle, you can check
function submitPrice() {
var $pricesubmitted = document.getElementById("inputvalue");
document.getElementById("submittedprice").innerText = $pricesubmitted.value;
}
function startAuction() {
var msgElement = document.getElementById("showMessage");
msgElement.innerText = "Count Down Started..";
var _el = document.getElementById("inputvalue");
var $startingprice = parseInt(_el.value);
var $bidcountdown = setInterval(function() {
msgElement.innerText = "Count Value " + $startingprice;
$startingprice--;
msgElement.innerText = $startingprice;
if ($startingprice < 0) {
msgElement.innerText = "Count Down ends ...";
clearInterval($bidcountdown);
}
}, 1000);
}
<span style="font-size: 36pt; font-family: homiziothin; color: black; padding-right: 20px;">£</span>
<input id="inputvalue" type="number" name="Value" min="0" max="500" value="">
<button id="commitprice" onclick="submitPrice()">Commit Price</button>
<p id="submittedprice"></p>
<button id="startauction" type="button" onclick="startAuction()">Start Auction</button>
<div id="showMessage"></div>
jsfiddle link

You have a couple of issues in your code. First, as noted by Mladen, you should be using .value instead of .textContent. Second, you should not use the "#" in the .getElementById selector.
This should fix it for you.
function startAuction()
{
debugger;
var $startingprice = document.getElementById("inputvalue").value;
var $bidcountdown = setInterval(function()
{
$startingprice--;
// document.getElementById("inputvalue").value = $startingprice;
document.getElementById("submittedprice").innerHTML= $startingprice;
if($startingprice <= 0)
clearInterval($bidcountdown);
}, 1000);
}
By the way, I highly recommend not jumping back and forth between jQuery and vanilla JS DOM selectors to avoid this kind of confusion.
Edit:
Commented out the line targeting the text input and added a line targeting the <p> tag. Note that instead of .value, you will need to use .innerHTML to make the change to the <p> tag (because it is updating the HTML contained within the opening and classing brackets of the <p>).

Related

Javascript eval() input field and output answer in same field

I am learning and want to know if there is a way to do this, let's say I have HTML input field:
<input type=text id="input">
Nearby I would have one button:
<button id="equal">=</button>
I want to write javaScript that would evaluate statement (if it is an equation like "2+3" "6/2" etc) in that text field and replace that statement with an answer for the equation. What I tried:
var equal = document.querySelector("#equal");
var input = document.querySelector("#input");
equal.addEventListener('click', function () {
eval(input.value) += input.innerText;
});
I already made only possible input 1234567890 and /*-+
If there is a way, I would highly appreciate the answer with explanation, started javaScript just recently so it is still like a dark forest for me, but I do have a wish to have a better understanding of it. :)
You just need to swap eval(input.value) += input.innerText to input.value = eval(input.value)
var equal = document.querySelector("#equal");
var input = document.querySelector("#input");
equal.addEventListener('click', function() {
input.value = eval(input.value);
});
<input type=text id="input">
<button id="equal">=</button>
Also, it would be recommended to use document.getElementById instead of document.querySelector, though there isn't much difference (mainly compatibility with older browsers). Read more
You want the place where you type in the expression to be different than the place where you display it:
<!DOCTYPE html>
<html>
<body>
<button id="evaluate">Get answer</button>
<input id="input" />
<p id="result">waiting for answer...</p>
<script>
var evaluate = document.getElementById("evaluate");
var input = document.getElementById("input");
var result = document.getElementById("result");
evaluate.addEventListener('click', function () {
try {
result.textContent = eval(input.value);
}
catch (error) {
result.textContent = "waiting for answer...";
}
});
</script>
</body>
</html>

Display output to multiple classes via JavaScript

I am writing a "Gamebook Engine" which offers the possibility of setting a user name. The Name is taken from an input with the id="setUserNameInput" and saved by the function setUserName(). It is displayed / loaded into an element containing the class="displayUserName" and loaded by the function displayUserName(). It works fine with only one class one the page, but as soon as I add more I have to define which one to target as it won't target them all automatically. I have tried to use document.getElementById, document.getElementsByName as well as document.querySelectorAll and document.querySelector, none of which work. (I use Bulma as my CSS Framework, by the way)
Here is the code I have so far (though it will show an error as it cannot access the localStorage inside the snippet):
This page http://scampsblog.com/docs/example-de.html contains an (working, haha) example. Since it is a documentation (page lies on my testing sever, thus the domain) you might want to take a look at http://scampsblog.com/docs/character-enginedotjs-de.html which explains / shows the individual elements (the documentation is in German but I can provide a translation if you need one).
The part of the JS I am struggling with is right in the first line but if you suggest some overall improvements, I will be happy to take them.
var userNameOutput = document.getElementsByClassName('displayUserName')[0];
function setUserName() {
var usernameinput = document.getElementById('setUserNameInput').value;
localStorage.setItem('userName', usernameinput);
if (!localStorage.getItem('userName')) {
setUserName();
} else {
var storedUserName = localStorage.getItem('userName');
userNameOutput.innerHTML = storedUserName;
}
}
function displayUserName() {
if (!localStorage.getItem('userName')) {
setUserName();
} else {
var storedUserName = localStorage.getItem('userName');
userNameOutput.innerHTML = storedUserName;
}
}
window.onload = function displayUserName() {
if (!localStorage.getItem('userName')) {
setUserName();
} else {
var storedUserName = localStorage.getItem('userName');
userNameOutput.innerHTML = storedUserName;
}
}
<input type="text" class="input" placeholder="Your name goes here" id="setUserNameInput">
<input type="button" class="button" value="Set your username" onclick="setUserName()" />
<input type="button" class="button" value="Display on click" onclick="displayUserName()" />
<br> So you shall be called <span class="displayUserName"></span>! But dont worry, <span class="displayUserName"></span>, it will be all fine.
Instead of getting the first item in the collection (using [0]) you could iterate through it (using for...of) and set the innerHTML of each element having the class displayUserName.
e.g.
var userNameOutputs = document.querySelectorAll('.displayUserName');
for (let ele of userNameOutputs) {
ele.innerHTML = userName;
}
Full code, with some optimizations to structure:
function setUserName() {
var usernameinput = document.getElementById('setUserNameInput').value;
localStorage.setItem('userName', usernameinput);
displayUserName(true); // pass true to avoid recursion
}
function displayUserName(skipSet) {
var userName = localStorage.getItem('userName');
if (!userName && !skipSet) {
setUserName();
} else {
var userNameOutputs = document.querySelectorAll('.displayUserName');
for (let ele of userNameOutputs) {
ele.innerHTML = userName;
}
}
}
window.onload = displayUserName;
<input type="text" class="input" placeholder="Your name goes here" id="setUserNameInput">
<input type="button" class="button" value="Set your username" onclick="setUserName()" />
<input type="button" class="button" value="Display on click" onclick="displayUserName()" />
<br> So you shall be called <span class="displayUserName"></span>! But dont worry, <span class="displayUserName"></span>, it will be all fine.
Working fiddle: https://jsfiddle.net/hosney/3pxfybrc/1/
var userNameOutput = document.getElementsByClassName('displayUserName')[0];
the [0] selects the first element of the array of elements of the class name.

Jquery Not working to create new Inputs

Below is my Html Doc and the JQuery does not do anything when the range input changes, any assistance is much appreciated as I am extremely new to web design. Even the alert doesn't work at the top so I am unsure as to what my problem is. My belief is somehow the script is never being called or it's a problem with it being an html doc but either way thank you.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var num=0;
var numOptions = new Array(100);
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
$(document).ready(function(){
$("#numQuestions").on('input',function(){
var numbQuestions = $("#numQuestions".text());
if(num>numbQuestions){
for(i=numbQuestions;i<=num;i++){
try{
$("#qRowNum'+i).remove();
}catch(err){
}
}
}else{
for ( i=num; i < numbQuestions; i++)
{
var row = '<div id="qRowNum'+ i '">
#the below function is not implemented in this version
<input type="text" placeholder="Question '+i'"> <input type="range" name="numOptions'+i'" min="0" max="5" placeholder="Number Of Options" onchange="CreateOptions(this);" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();> </div>';
$("#questionRows").append(row);
//New script test
}
}
num = numbQuestions;
});
});
<div id="questionRows">
</div>
<input type="submit" value="Start">
</form>
</body>
</html>
This is your problem:
var numbQuestions = $("#numQuestions".text());
Firstly I think you mean this:
var numbQuestions = $("#numQuestions").text();
But that is also not true because an input field has not text property. They have value So do this:
var numbQuestions = $("#numQuestions").val();
And this is another problem: $("#qRowNum'+i) When you start selector by double quotation, you need to end this also by double quotation. But it still is not a true jquery selector.
I think you need to more studies about jquery.

Character Counter for multiple text areas

I have a form that has 3 text areas, a copy button, and a reset button. I want to add all the characters to one sum, then display that sum next to the copy/reset button. There is a 500 character limit, and the counter should start at 49 characters. Should I just take all my textareas and "Funnel" them into a var, then count that var? I'm not sure how I should approach this. I've tried this technique
but it only works with one text area, not the sum of all. If the char count goes above 500, I'd like the text to turn red and say "you've gone over your character limit." I do not want to restrict or limit the text once its over 500. I'm a little fried trying to find a solution, and I'm an obvious html/javascript novice.
I do not need to worry about the carriage return issue in firefox/opera since everyone will be using IE11.
<h1>
Enter your notes into the text boxes below
</h1>
<p>
Please avoid using too many abbreviations so others can read your notes.
</p>
<form>
<script type="text/javascript"><!--
// input field descriptions
var desc = new Array();
desc['kcall'] = 'Reason for Call';
desc['pact'] = 'Actions Taken';
desc['mrec'] = 'Recommendations';
function CopyFields(){
var copytext = '';
for(var i = 0; i < arguments.length; i++){
copytext += desc[arguments[i]] + ': ' + document.getElementById (arguments[i]).value + '\n';
}
var tempstore = document.getElementById(arguments[0]).value;
document.getElementById(arguments[0]).value = copytext;
document.getElementById(arguments[0]).focus();
document.getElementById(arguments[0]).select();
document.execCommand('Copy');
document.getElementById(arguments[0]).value = tempstore;
document.getElementById("copytext").reset();
}
--></script>
<p> Reason For Call: </p> <textarea rows="5" cols="40" id="kcall"></textarea><br>
<p> Actions Taken: </p> <textarea rows="5" cols="40" id="pact"></textarea><br>
<p> Recommendations: </p> <textarea rows="5" cols="40" id="mrec"></textarea><br>
<br>
<button type="button" onclick="CopyFields('kcall', 'pact', 'mrec');">Copy Notes</button>
<input type="reset" value="Reset"/>
</form>
I think this question is a little more tricky that you think, and is not cause the complex of count the number of character inside of a textarea thats is actually pretty simple. in jquery:
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
The problem begins whit the keyup event since and how you manage that event, in my follow example, I pretty much manage when the user press the key like in regular state but if you start holding a key then stoping and copy and paste really quick, the event get lost a little bit and recover after the second keyup. Any way here is my full example with count of character counter, change from red to black and black to red if you over pass the max characters and validation for submit or not the form
Fiddle:
https://jsfiddle.net/t535famp/
HTML
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<button class="reset"></button>
You have use <span class="characters"></span> of <span class="max"></span>
<button class="submit">submit</button>
JS
$(function(){
var counter = 0; //you can initialize it with any number
var max = 400; //you can change this
var $characters = $(".characters");
var $max = $(".max");
var submit = true;
$characters.html(counter);
$(".max").html(max);
function count(event){
var characters = $(event.target).val().length;
$characters.html(counter);
//sum the textareas
var sum = 0;
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
counter = sum;
if(counter > max) {
$characters.css({ color : "red" });
submit = false;
}else{
$characters.css({ color : "black" });
submit = true;
}
}
$(document).on("keyup","textarea",count);
$(document).on("click",".submit",function(){
if(submit)
alert("done");
else
alert("you have more characters than " + max);
});
})
Good luck my 2 cents
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
That will return the count of all textareas on the page. Change the querySelector to be more specific if you only want to count specific textareas.
One option would be to add onchange events to your textareas which call a function like below:
<script>
function validate() {
if(textareaLength() >= 500) {
//limit reached
}
}
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
</script>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
Count
Here's a really simple function:
function TextLength() {
return Array.prototype.reduce.call(
document.querySelectorAll('textarea'),
function(b,a) { return b+a.value.length }, 0);
}
Or with ES6:
const TextLength = () => Array.from(document.querySelectorAll('textarea')).reduce((b,a) => b + a.value.length, 0)
To use this:
TextLength();
Change
Now add this:
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (e) { e.oninput = TextLength });
And again, ES6:
Array.from(document.querySelectorAll('textarea')).forEach(e => e.oninput = TextLength );
Since the button is in the same form as the textarea elements, you can get a reference to the form using the button's form property. You can also get all the text area elements in the form using querySelectorAll, then loop over them, adding up the characters in each.
The following just counts the total number of characters in the textarea elements:
<button type="button" onclick="count(this)">Copy Notes</button>
and the function:
function count(el) {
var tas = el.form.querySelectorAll('textarea');
var numChars = 0;
for (var i=0, iLen=tas.length; i<iLen, I++) {
numChars += tas[i].value.length;
}
return numChars;
}
If you can rely on ES5+ methods, then you can do:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
Note that by convention, functions starting with a capital letter are reserved for constructors, so CopyFields should be copyFields.
Here's a working example:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
<form>
<textarea name="ta0"></textarea>
<textarea name="ta1"></textarea>
<textarea name="ta2"></textarea><br>
<input type="text" name="numChars">
<button type="button" onclick="this.form.numChars.value = count(this)">count</button>
<input type="reset">
</form>
If you have more than one textarea (Multiple) and you want to display character count on each textarea, you may try below code, as its working me like a charm.
$(document).ready(function () {
$('textarea').on("load propertychange keyup input paste",
function () {
var cc = $(this).val().length;
var id=$(this,'textarea').attr('id');
$('#'+id).next('p').text('character Count: '+cc);
});
$('textarea').trigger('load');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id="one">hello</textarea>
<p></p>
<textarea id="two"></textarea>
<p></p>
<textarea id="three"></textarea>
<p></p>

Dynamically adding HTML form fields based on a number specified by the user [duplicate]

This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 1 year ago.
I've a form field named Number of messages, and based on what number the user specifies, I want the exact number of text fields to be dynamically generated below to allow users to enter specified number of messages.
I have browsed through some examples where JQuery is used to generate dynamic form fields, but since I'm not acquainted with JQuery, those examples are a bit too complex for me to grasp. I do know the basics of JavaScript, and would really appreciate if I could find a solution to my query using JavaScript.
function addinputFields(){
var number = document.getElementById("member").value;
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
and html code will be
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
fiddle here
You can try something similar to this...
var wrapper_div = document.getElementById('input_set');
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var n = document.getElementById("no_of_fields").value;
var fieldset = document.createElement('div'),
newInput;
for (var k = 0; k < n; k++) {
newInput = document.createElement('input');
newInput.value = '';
newInput.type = 'text';
newInput.placeholder = "Textfield no. " + k;
fieldset.appendChild(newInput);
fieldset.appendChild(document.createElement('br'));
}
wrapper_div.insertBefore(fieldset, this);
}, false);
No. of textfields :
<input id="no_of_fields" type="text" />
<div id="input_set">
<p>
<label for="my_input"></label>
</p>
<button id="btn" href="#">Add</button>
</div>
It is a simple task which is made simpler with jQuery. You need to first get the value from the input field for which you can use .val() or .value. Once you get the value, check if it is an integer. Now, simply use .append() function to dynamically add the elements.
HTML
<form id="myForm">
Number of Messages: <input id="msgs" type="text"> </input>
<div id="addmsg">
</div>
</form>
JAVASCRIPT
$("#msgs").on('change', function()
{
var num = this.value;
if(Math.floor(num) == num && $.isNumeric(num))
{
$("#addmsg").text('');
for(var i = 0; i < num; i++)
{
$("#addmsg").append("<input type='text'/><br/>");
}
}
});
Fiddle
Note, everytime the value in the input changes, I am first clearing the div by:
$("#addmsg").text('');
And then I loop and keep adding the input field. I hope this helps!

Categories

Resources