how to change the div value with a counter - html

I don't understand why this function does not change the value of num every time I press the button. basically i wanted to make a counter that adds one to the div every time i press the button.
<div class="elements" id="txtthrow">0</div>
<button class="button1" id="buttonNewHand" onclick="newFaceTot()">new<br>number</button>
//------------------------------------------------------------------------
refthrow = document.getElementById("txtthrow");
function newFaceTot(){
numberChanged();
}
function numberChanged(){
var num = parseInt(refthrow.value, 10);
refthrow.innerHTML = changeNumber(num);
}
function changeNumber(num){
num = num + 1;
return num;
}

Only form (e.g. input/select/textarea) elements have a value. For other elements use innerHTML or innerText to get the content.
const refthrow = document.getElementById("txtthrow");
function newFaceTot() {
numberChanged();
}
function numberChanged() {
var num = parseInt(refthrow.innerText, 10);
refthrow.innerHTML = changeNumber(num);
}
function changeNumber(num) {
num = num + 1;
return num;
}
<div class="elements" id="txtthrow">0</div>
<button class="button1" id="buttonNewHand" onclick="newFaceTot()">new<br>number</button>
Therefore the value attribute was undefined. And parseInt(undefined) is NaN (not a number).

Related

Countdown using astrisk

Currently it shows smallest to biggest. I want it start from biggest to smallest, can't figure it out.
Current output of code
Sample run:
Input to text box: 3
Output in div:
[*]
[**]
[***]
And that’s all folks!
Desired output of code
Sample Run:
Input to text box: 3
Output in div:
[***]
[**
[*]
And that’s all folks!
<!doctype html>
<!—This code will produce a triangle of stars -->
<!-- ================================== -->
<html>
<head>
<title> Countdown </title>
<script type="text/javascript">
function Countdown() {
var count, astrisk;
i=1;
//j=0;
count = parseFloat(document.getElementById('countBox').value);
document.getElementById('outputDiv').innerHTML = '';
astrisk = '*'
while (i<count) {
j=0;
while (j<i) {
document.getElementById('outputDiv').innerHTML =
document.getElementById('outputDiv').innerHTML + astrisk ;
j=j+1;
}
document.getElementById('outputDiv').innerHTML =
document.getElementById('outputDiv').innerHTML + '<br>';
i=i+1;
}
document.getElementById('outputDiv').innerHTML =
document.getElementById('outputDiv').innerHTML + 'And that\'s all folks!' + '<br>';
}
</script>
</head>
<body>
<p>
Start of the countdown:
<input type="text" id="countBox" size=4 value=10>
</p>
<input type="button" value="Begin Countdown" onclick="Countdown();">
<hr>
<div id="outputDiv"></div>
</body>
</html>
I tried flipping some variables, couldn't exactly get it to do what I want. Most of my attempts have led to my computer crashing, I feel like answer is there, but I can't exactly see it. code isn't properly formatted, spent 2 hours trying to indent correctly, and eventually I gave up.
Get the input, button and p (output)
Add click event to the button
When the button is clicked, get input.value plus 1 since it's automatically decreased at the beginning of the function
Print to the DOM the asterisk repeated by the value (that is decreased every 1 second).
When the value reaches 0, clear the function.
let btn = document.querySelector('button');
let input = document.querySelector('input');
let output = document.querySelector('p');
// Button onclick
btn.addEventListener('click', () => {
// Save the run time (input value + 1) since it's automatically decreased at run-time
let timesRun = Number(input.value) + 1;
// Disable the button when it's counting
btn.disabled = true;
// Repeated function every 1 second
let interval = setInterval(function(){
// Decrease the run time
timesRun -= 1;
// If reaches 0, clear the function
if(timesRun === 0){
btn.disabled = false;
clearInterval(interval);
output.innerHTML = 'TIMEOUT';
// Else? print the * repeated by times remain
} else {
output.innerHTML = '*'.repeat(timesRun);
}
}, 1000);
});
<input type="number" placeholder="Countdown" />
<button>Start</button>
<div>
<p></p>
</div>
Updated with the following conditions:
Check that the input is a valid number and not empty
Accept a number between 1 and 10 (including)
let btn = document.querySelector('button');
let input = document.querySelector('input');
let output = document.querySelector('p');
// Button onclick
btn.addEventListener('click', () => {
// Check it's a valid nubmer and not empty
if(input.value.length === 0 || isNaN(Number(input.value))) {
output.innerHTML = 'Please type a valid number.';
// Check if the number is between 1 and 10
} else if (Number(input.value) <= 0 || Number(input.value) > 10) {
output.innerHTML = 'Please type a number between 1-10';
} else {
// Save the run time (input value + 1) since it's automatically decreased at run-time
let timesRun = Number(input.value) + 1;
// Disable the button when it's counting
btn.disabled = true;
// Repeated function every 1 second
let interval = setInterval(function(){
// Decrease the run time
timesRun -= 1;
// If reaches 0, clear the function
if(timesRun === 0){
btn.disabled = false;
clearInterval(interval);
output.innerHTML = 'TIMEOUT';
// Else? print the * repeated by times remain
} else {
output.innerHTML = '*'.repeat(timesRun);
}
}, 1000);
}
});
<input type="number" placeholder="Countdown" />
<button>Start</button>
<div>
<p></p>
</div>

Why does this Javascript function rewrite the innerHTML of one div but not the other?

I'm using NodeJS to query a MySQL database for a single entry of a journal, but the results aren't going to both of the assigned divs. I have an iFrame in my center column, dedicated to two divs (one hidden at any given time). One div is a read-only page for the journal entry, and the other one contains a TinyMCE rich-text editor. I have buttons in left column to switch between the views.
The rich-text editor loads properly on initial load of page, but doesn't update as I navigate with the calendar; the read-only innerHTML does update properly as I navigate.
calDt[] is an array that holds dates. calDt[0] is the active date, while calDt[1] holds a dummy date used for navigating the calendar without changing the entry.
app.js:
app.get('/getdata/:dateday', (req, res) => {
let sql = `SELECT entry FROM main where dateID ='${req.params.dateday}'`
let query = db.query(sql, (err, results) => {
if(err) {
throw err
}
res.send(JSON.stringify(results));
})
})
middle-left.ejs
<button style= "height:22px"; type="button" onclick="readDivHere()">Lock</button>
<button style= "height:22px"; type="button" onclick="editDivHere()">Edit</button></div>
<script> // the Lock button brings us back to the completed entry in the middle stuff
function readDivHere() {
document.getElementById('frame1').contentWindow.readDivHere();
document.getElementById('frame1').scrolling = "yes";
}
</script>
<script> // the Edit button will bring tinymce rich-text editor to the middle stuff
function editDivHere() {
document.getElementById('frame1').contentWindow.editDivHere();
document.getElementById('frame1').scrolling = "no";
}
</script>
middle-center.ejs
<iframe id="frame1" class="entryon" src="" frameborder="0px"></iframe>
<script>
document.getElementById("frame1").src = "iframe";
</script>
iframe.ejs
<div id="readDiv" class="here" style="display: block; background: white; padding-top: 0px; padding-left: 10px; padding-right: 8px; min-height: 810px; width: 967px;"><%- include ('entry'); %></div>
<div id="editDiv" class="here" style="display: none; padding: 0px;" ><%- include ('editPage'); %></div>
<script> //function that switches from rich-text editor back to real entry
function readDivHere() { // here we run a function to update text of read-only entry
document.getElementById("readDiv").style.display="block";
document.getElementById("editDiv").style.display="none";
}
</script>
<script> //function that switches from read-only entry to rich-text editor
function editDivHere() {
document.getElementById("readDiv").style.display="none";
document.getElementById("editDiv").style.display="block";
}
</script>
entry.ejs
<div id="readOnlyEntry"></div>
<script>
// load the active entry into the middle column for proper reading
function loadEntry(p) {
var x = parent.calDt[1].getFullYear();
var y = parent.calDt[1].getMonth();
y = y + 1;
if (y < 10) {
y = "0" + y;
};
if (p < 10) {
p = "0" + p;
}
var newDate = x + "" + y + "" + p; // p is a date formatted like 20210808
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                const text = this.responseText;
                const obj = JSON.parse(text);
document.getElementById("readOnlyEntry").innerHTML = obj[0].entry;
document.getElementById("richTextEd").innerHTML = obj[0].entry; // doesn't work!
            }
xhttp.open("GET", "../getdata/" + newDate, true);
        xhttp.send();
}
</script>
<script>
// rich-text editor populates correctly on load
loadEntry(parent.calDt[0].getDate());
</script>
editPage.ejs
<%- include ('tinymce'); %>
<form method="POST" action="../result" enctype="multipart/form-data">
<textarea name="content" id="richTextEd">Here's the default text.</textarea>
</form>
calendar-clicker.ejs
var p = x.innerHTML; // get the value of the calendar cell text (i.e. day of the month)
p = p.match(/\>(.*)\</)[1];
var d = calDt[1].getFullYear(); // what year is the calendar referencing?
var q = calDt[1].getMonth(); // what month is the calendar referencing?
q = q + 1; // compensate for javascript's weird month offset
calDt[0] = new Date(q + "/" + p + "/" + d); // assign a new global date variable
calDt[1] = calDt[0]; // temporarily reset navigation date to active date
document.getElementById('frame1').contentWindow.loadEntry(p);
Does the failure have to do with assigning the innerHTML to a different .ejs? If I put the form into the same div as the read-only entry, the form still fails to update as I navigate.
Solved it.
In entry.ejs, I replaced...
document.getElementById("richTextEd").innerHTML = obj[0].entry;
with
tinymce.get("richTextEd").setContent(obj[0].entry);
https://www.tiny.cloud/blog/how-to-get-content-and-set-content-in-tinymce/

My ajax countdown doesn't work as it should?

I have here AJAX + HTML and it seems not to be working as it should.
Basically it (work with / use) only the first number (count) and it seems like the rest is forgotten?
My code
<script id="ajax">
var count = 200;
var counter = setInterval(a2, 1000);
function a2() {
count = count - 1;
if (count < 0) {
clearInterval(counter);
return;
}
document.getElementById("a2").innerHTML = count;
}
</script>
<div id="a2"></div>
<script id="ajax">
var count = 100;
var counter = setInterval(a3, 1000);
function a3() {
count = count - 1;
if (count < 0) {
clearInterval(counter);
return;
}
document.getElementById("a3").innerHTML = count;
}
</script>
<div id="a3"></div>
Anyone knows what could be the issue? I feel like I'm totally lost.
Issue no2:
When I push the script into a real-usage, it only seems to execute the first script/code and the next script is being executed after the first script time is runs over. Therefore it second timer appears to be blank if first one is running.
It does work though when I manually put the script into the console.
Any ideas?
Thank you!
The problem here is var in JS is function scoped. Since you used it out of a function, it is pretty much global throughout the whole script. How about you make the counter implementation into a function and call it like this?
<script id="ajax">
function counter (elem, count) {
var counter = setInterval(func, 1000);
function func() {
count = count - 1;
if (count < 0) {
clearInterval(counter);
return;
}
document.getElementById(elem).innerHTML = count;
}
}
counter("a2", 200);
</script>
<div id="a2"></div>
<script id="ajax">
counter("a3", 100);
</script>
<div id="a3"></div>
No, you should add two codes in one setInterval function for executing on same time:
var count1=10;
var count2=5;
var counter=setInterval(a2, 1000);
function a2()
{
if (count1 != 0)
{
count1--;
//Some functions that are dependent of count1, eg.
if(count1==3){document.getElementById("a2").style.color="red";}
}
if (count2 != 0)
{
count2--;
//Some functions that are dependent of count2 eg.
if(count2==3){document.getElementById("a3").style.color="red";}
}
if(count1==0 && count2==0){
clearInterval(counter);
}
console.log('counting!');
document.getElementById("a2").innerHTML=count1;
document.getElementById("a3").innerHTML=count2;
}
<div id="a2"></div>
<div id="a3"></div>
If you have two different functions that are dependent of counters then go with above code
Try this one
var count_a2 = 200;
var counter_a2 = setInterval(a2, 1000);
function a2() {
count_a2 = count_a2 - 1;
if (count_a2 < 0) {
clearInterval(counter_a2);
return;
}
document.getElementById("a2").innerHTML = count_a2;
}
var count = 100;
var counter = setInterval(a3, 1000);
function a3() {
count = count - 1;
if (count < 0) {
clearInterval(counter);
return;
}
document.getElementById("a3").innerHTML = count;
}
<div id="a2"></div>
<div id="a3"></div>

Add 2 input values and show total

I have 2 'time' inputs for a start and end time.
When both inputs are completed I am wanting the 'total' field to automatically show the total between start and end (e.g 8 hours)
<input type='time' value="09:00" id="MondayStart" name='MondayStart' class='form-control'>
<input type='time' value="17:00" name='MondayEnd' id="MondayEnd" class='form-control'>
<input type="text" name="total">
I have tried following this script (http://jsbin.com/emoziw/1/edit?html,js,output) but cannot seem to change it to time
You have a default value so this is good.
You need to do something like this (using jQuery) :
$(".form-control").on('change', ()=>{
var $this = $(this);
var sum;
sum = /*do the sum calculation here*/;
$('input[name="total"]').eq(0).val(sum);
//if you put an id to the total then you can just use $(id here).val(sum)
});
This will, when the change event is triggered on any element having the form-control class, update the sum automatically.
PS:
I suggest to put a default value on the sum's holder (being of course the sume of the default values)
EDIT
I'd like to help you with the time calculation, so I made functions :
function doCalc($jq){//pass in the jqSelection that gets the two input
var $beg = $jq.eq(0);//first element with this class
var $end = $jq.eq(1);//second element with this class
var beg_t = {
h: getH($beg),
m: getM($beg)
}
var end_t = {
h: getH($end),
m: getM($end)
}
var elapsed = {
h: end_t.h - beg_t.h,
m: end_t.m - beg_t.m
}
return ""+elapsed.h+":"+elapsed.m;//so it can be used with what's above
}
/
function getH($t){
var str = $t.val();
return str.replace(/(\d{2}):(\d{2})/,"$1");
}
function getM($t){
var str = $t.val();
return str.replace(/(\d{2}:(\d{2})/,"$2");
}
EDIT 2:
If you want you can pass to the onchange EH a function pointer (therefore you can also call the function without having to trigger the event) :
function updateSum(){
var $this = $(".form-control");
var sum;
sum = doCalc($this);
$('input[name="total"]').eq(0).val(sum);
//if you put an id to the total then you can just use $(id here).val(sum)
}
therefore you can have :
$(document).ready(()=>{
updateSum();
$(".form-control").on('change', updateSum);
});
EDIT 3:
()=>{/*...*/} is just the ES6 way to declare an anonymous function, you can replace them with function(){/*...*/} if you're more comfortable with it.
EDIT 4 aka RECAP :
If you're a bit lost after this answer, here's a recap of the functions you need to add to your website :
##Regex based input processing##
function getH($t){
var str = $t.val();
return str.replace(/(\d{2}):(\d{2})/,"$1");
}
function getM($t){
var str = $t.val();
return str.replace(/(\d{2}:(\d{2})/,"$2");
}
##Calculation##
function doCalc($jq){//pass in the jqSelection that gets the two input
var $beg = $jq.eq(0);//first element with this class
var $end = $jq.eq(1);//second element with this class
var beg_t = {
h: getH($beg),
m: getM($beg)
}
var end_t = {
h: getH($end),
m: getM($end)
}
var elapsed = {
h: end_t.h - beg_t.h,
m: end_t.m - beg_t.m
}
return ""+elapsed.h+":"+elapsed.m;//so it can be used with what's above
}
##Update function##
function updateSum(){
var $this = $(".form-control");
var sum;
sum = doCalc($this);
$('input[name="total"]').eq(0).val(sum);
//if you put an id to the total then you can just use $(id here).val(sum)
}
##Event Handling and Call##
$(document).ready(function(){
updateSum();
$(".form-control").on('change', updateSum);
});

getelementbyid issue with radio button

I'm trying to make an alert with the value of the selected radio button, but I allways get the first of them, regardless the one I choose...(Acompanhado);
html:
<form/>
<input type="radio" class="simple_form" name="grupo_1" value="Acompanhado" id="saida"/>
<span class="texto">Acompanhado</span>
<input type="radio" class="simple_form" name="grupo_1" value="Individual" id="saida"/>
<span class="texto">Individual</span>
</form>
js:
function save() {
var saida_js = document.getElementById('saida').value;
alert("Tipo de saida: " + saida_js);
}
Any idea ?
#Quentin: I have alot of alerts, cause Im trying to get all data from a form. I used your code, and I get no alert at all.
function save() {
var morada_js = document.getElementById('morada').value;
var data_js = document.getElementById('data').value;
var hora_js = document.getElementById('hora').value;
var radio_saida = document.getElementsByName('name_saida');
var notas_js = document.getElementById('notas').value;
var condicoes_atm_js = document.getElementById('condicoes_atm').value;
alert("Morada: " + morada_js);
alert("Data: " + data_js);
alert("Hora: " + hora_js);
function get_checked_radio(radio_saida) {
for (var i = 0; i < radio_saida.length; i++) {
var current = radio_saida[i];
if (current.checked) {
return current;
}
}
}
alert(get_checked_radio(radio_saida).value);
alert("Notas: " + notas_js);
}
An id must be unique in a document.
To find the value of a selected radio button in a group, get the group by its name…
var radios = document.getElementsByName('radio_name'); // or
var radios = document.forms.formId.elements.radio_name;
Then loop over them until you find the one with the true checked property.
function get_checked_radio(radios) {
for (var i = 0; i < radios.length; i++) {
var current = radios[i];
if (current.checked) {
return current;
}
}
}
alert(get_checked_radio(radios).value);
Makes sense because you've got two input tags with the same id saida