This simple code is supposed to give an alert when the button is pressed the amount of times you wrote in the input. There is no error or something but the code just doesn't work. Am I stupid and did I miss something or is the logic of my code just wrong? and how do make it work?
var rand1, rand2, text1, text2
let count = 0;
var correct = 0;
function button(){
text1 = document.getElementById("number").value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check(){
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if(answer == text11) {
var h = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
correct = correct + 1;
count = count + 1;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count === text2){
alert(correct + '/' + text2);
}
function wait(){
button()
}
}
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id = 'but'> ok </button>
<div id = 'div'> </div>
The .value returns a string and you must convert it into a number (if you want to) before using it.
So in line 6 do this:
text1 = Number(document.getElementById("number").value);
and also in the check() function:
text2 = Number(document.getElementById('questions').value);
Hope that works.
How to create datalist dynamically?
Was able to dynamically create a drop down using create element and append child but am struggling with datalist.
<script>
let counter = 0;
function myFunction3() {
if (counter < 5) {
counter++;
/*var text = document.createElement("TEXTAREA");
text.id = "text" + counter;
document.body.appendChild(text);*/
var drdwn = document.createElement("datalist");
drdwn.id = "drdwn" + counter;
document.body.appendChild(drdwn);
var opt1 = document.createElement("option");
opt1.text = "<";
opt1.value = "<";
document.getElementById("drdwn" + counter).appendChild(opt1);
var opt2 = document.createElement("option");
opt2.text = ">";
opt2.value = ">";
document.getElementById("drdwn" + counter).appendChild(opt2);
var opt3 = document.createElement("option");
opt3.text = "=";
opt3.value = "=";
document.getElementById("drdwn" + counter).appendChild(opt3);
/*var value = document.createElement("TEXTAREA");
value.id = "value" + counter;
document.body.appendChild(value);*/
}
}
</script>
const options = document.querySelector('.options');
const datalistCreator = document.querySelector('.datalist-creator');
const datalistsBlock = document.querySelector('.datalists');
let counter = 0;
datalistCreator.addEventListener('click', function() {
const datalist = document.createElement('datalist');
const output = document.createElement('input');
datalist.setAttribute('id', 'datalist' + counter);
output.setAttribute('list', 'datalist' + counter);
output.placeholder = 'Datalist of ' + options.value;
for (let i = 0; i < options.value; i++) {
const option = document.createElement('option');
option.value = i + 1;
datalist.appendChild(option)
}
datalistsBlock.appendChild(datalist);
datalistsBlock.appendChild(output);
counter++;
return output;
})
<input type="text" class="options">
<button class="datalist-creator">Create datalist</button>
<div class="datalists"></div>
I want to add a if condition in my text field that if my text field is empty and send button is clicked the empty bubble shouldn't go.
function typo(){
var currentText = document.getElementById("demo").innerHTML;
var x = '<div><p class=bubble>' + document.getElementById("myText").value + '</p></div>';
document.getElementById("myText").value = "";
var y = document.getElementById("demo").innerHTML = currentText + x;
var z = document.getElementById('demo');
z.scrollTop = z.scrollHeight;
document.getElementById("myText").focus();
}
<input class="widebox" type="text" id="myText" value="">
<button onclick="typo()" class="btn btn-warning btn-sm" id="btn-chat">Send</button>
This is the demo for what am been trying to do. Thanks
You can check the length of the value.
function typo() {
if (document.getElementById("myText").value.length == 0) {
// give error message
} else {
var currentText = document.getElementById("demo").innerHTML;
var x = '<div><p class=bubble>' + document.getElementById("myText").value + '</p></div>';
document.getElementById("myText").value = "";
var y = document.getElementById("demo").innerHTML = currentText + x;
var z = document.getElementById('demo');
z.scrollTop = z.scrollHeight;
document.getElementById("myText").focus();
}
}
Your code should look like this :
if ( document.getElementById("Textfield").value)
{the code that sends the content}
And if you are adding this in a .html file just enclose the code in the script tags.
Check this fiddle https://jsfiddle.net/kkjbryqe/35/
function typo(){
var x,y,x;
var currentText = document.getElementById("demo").innerHTML;
var ans = document.getElementById("myText").value;
var val = ans.replace(/^\s+/, '').replace(/\s+$/, '');
if(val === ""){
}
else{
x = '<div><p class=bubble>' +
document.getElementById("myText").value + '</p></div>';
document.getElementById("myText").value = "";
y = document.getElementById("demo").innerHTML = currentText + x;
z = document.getElementById('demo');
z.scrollTop = z.scrollHeight;
}
}
I've created a calculator to show repayments over the term of the loan.
I've managed to calculate each months payment, interest, remaining loan but I'm trying to output this into a table. The columns will be a fixed number (5) but the rows should dynamically update based on the number of months.
I've seen a few similar posts but can't get it to work for my code.
Code below and in jsfiddle
HTML
<div class="mortgageInput">
<form method="POST" name="calc" onclick="validateForm();repayment();return false;">
<label>Amount </label>
<input type="textbox" id="loan" value="100000"><br>
<label>Years</label>
<input type="textbox" id="years" value="15"><br>
<label>Rate (%)</label>
<input type="textbox" id="rate" value="6.00" onkeyup="calculate"><br>
<input type="button" value="Calculate" id="btn"><br>
<label>Monthly Repayment</label>
<input type="textbox" id="monthlyRepayment"><br>
<label>Monthly Interest Only</label>
<input type="textbox" id="interest"><br>
<label>Monthly Capital Repayment</label>
<input type="textbox" id="capitalRepayment"><br>
<label>Total Interest</label>
<input type="textbox" id="totalInterest">
</form>
</div>
<br>
Output into table...<p id="demo"></p>
JS
(document).on("keyup", calculate());
function validateForm(){
var validation = true;
validation &= calculate();
validation &= pmt();
return validation;
}
function calculate() {
var p = document.querySelector("#loan").value;
var y = document.querySelector("#years").value;
var rate = document.querySelector("#rate").value;
var r = rate / 100 / 12;
var n = y * 12;
var I = (p * r);
var monthlyPayment = -pmt(r,n,p);
var mr = (monthlyPayment - I);
var ti = (monthlyPayment) * n - p;
var list = JSON.stringify((computeSchedule(p, rate, 12, y, monthlyPayment)), 0, 4);
document.querySelector("#interest").value = I.toFixed(2);
document.querySelector("#totalInterest").value = ti.toFixed(2);
document.querySelector("#capitalRepayment").value = mr.toFixed(2);
document.querySelector("#monthlyRepayment").value = monthlyPayment.toFixed(2);
document.getElementById("demo").innerHTML = list;
}
function pmt(rate,nper,pv) {
var pvif, pmt;
pvif = Math.pow( 1 + rate, nper);
pmt = rate / (pvif - 1) * -(pv * pvif);
return pmt;
}
function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
var schedule = [];
var remaining = loan_amount;
var number_of_payments = payments_per_year * years;
for (var i=0; i<=number_of_payments; i++) {
var interest = remaining * (interest_rate/100/payments_per_year);
var principle = (payment-interest);
var row = [i, payment, interest>0?interest:0, principle>0?principle:0, remaining>0?remaining:0];
schedule.push(row);
remaining -= principle
}
return schedule;
}
the above answer is right but if concern about performance do insert html outside loop
var list = computeSchedule(p, rate, 12, y, monthlyPayment);
var tables = "";
for (var i = 0; i < list.length; i++) {
tables += "<tr>" +
"<td>" + list[i][0] + "</td>" +
"<td>" + list[i][1] + "</td>" +
"<td>" + list[i][2] + "</td>" +
"<td>" + list[i][3] + "</td>" +
"<td>" + list[i][4] + "</td>" +
"</tr>";
}
document.getElementById("demo").innerHTML = '<table>' + tables + '</table>';
I am not sure if I understand you correctly, but this should normally be the solution. You're fiddle printed some js errors, I haven't fixed them in this example.
function validateForm(){
var validation = true;
validation &= calculate();
validation &= pmt();
return validation;
}
function calculate() {
var p = document.querySelector("#loan").value;
var y = document.querySelector("#years").value;
var rate = document.querySelector("#rate").value;
var r = rate / 100 / 12;
var n = y * 12;
var I = (p * r);
var monthlyPayment = -pmt(r,n,p);
var mr = (monthlyPayment - I);
var ti = (monthlyPayment) * n - p;
var list = JSON.stringify((computeSchedule(p, rate, 12, y, monthlyPayment)), 0, 4);
document.querySelector("#interest").value = I.toFixed(2);
document.querySelector("#totalInterest").value = ti.toFixed(2);
document.querySelector("#capitalRepayment").value = mr.toFixed(2);
document.querySelector("#monthlyRepayment").value = monthlyPayment.toFixed(2);
var list = computeSchedule(p, rate, 12, y, monthlyPayment);
console.log(list.length);
for (var i=0; i < list.length; i++) {
document.getElementById("test").innerHTML += "<tr><td>" + list[i][0] + "</td><td>" + list[i][1] + "</td><td>" + list[i][2] + "</td><td>" + list[i][3] + "</td><td>" + list[i][4] + "</td></tr>";
}
}
function pmt(rate,nper,pv) {
var pvif, pmt;
pvif = Math.pow( 1 + rate, nper);
pmt = rate / (pvif - 1) * -(pv * pvif);
return pmt;
}
function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
var schedule = [];
var remaining = loan_amount;
var number_of_payments = payments_per_year * years;
for (var i=0; i<=number_of_payments; i++) {
var interest = remaining * (interest_rate/100/payments_per_year);
var principle = (payment-interest);
var row = [i, payment, interest>0?interest:0, principle>0?principle:0, remaining>0?remaining:0];
schedule.push(row);
remaining -= principle
}
return schedule;
}
table {
border-spacing: 0;
}
table td {
border: 1px solid #666;
padding: 0 3px;
}
<div class="mortgageInput">
<form method="POST" name="calc" onclick="validateForm();repayment();return false;">
<label>Amount </label>
<input type="textbox" id="loan" value="100000"><br>
<label>Years</label>
<input type="textbox" id="years" value="15"><br>
<label>Rate (%)</label>
<input type="textbox" id="rate" value="6.00" onkeyup="calculate"><br>
<input type="button" value="Calculate" id="btn"><br>
<label>Monthly Repayment</label>
<input type="textbox" id="monthlyRepayment"><br>
<label>Monthly Interest Only</label>
<input type="textbox" id="interest"><br>
<label>Monthly Capital Repayment</label>
<input type="textbox" id="capitalRepayment"><br>
<label>Total Interest</label>
<input type="textbox" id="totalInterest">
</form>
</div>
<br>
<table id="test">
</table>
The result of computeSchedule contains a two dimensional array. You should be able to loop through it with two nested for loops. Then you can compose your table.
Very simple example would look like this:
var demoList = computeSchedule(p, rate, 12, y, monthlyPayment);
var table = "<table>";
for (var rowIndex=0; rowIndex <= n; rowIndex++) {
var row = "<tr><td>#" + rowIndex + "</td>";
for(var colIndex = 0; colIndex < 4; colIndex++) {
row += "<td>" + demoList[rowIndex][colIndex] + "</td>";
}
table += row + "</tr>";
}
document.getElementById("output").innerHTML = table + "</table>";
You can also try the life version here: https://fiddle.jshell.net/aua4g8e7/
I'm new to Javascript and working on a problem, it's about making a website that allows a user to input a bid on an item along with a bid id. When they input both they press the submit button and the bid/bid id (along with the date and time) will display in a textarea.
It should allow for multiple bids to be submitted and to display but currently I can only get one to display. Any help as to how I can get multiple bids to display would be appreciated. Thank you
var bids = new Array();
var bidders = new Array();
var bidTime = new Array();
function writeBid() {
var historyText = " ";
for (var i = 0; i < bids.length; i++) {
historyText = bidTime[i] + " " + bids[i] + " " + bidders[i] + "\n";
document.bidForm.bidList.value = historyText;
document.bidForm.highBid.value = bids[i];
document.bidForm.bidId.value = " ";
document.bidForm.bidAmount.value = " ";
}
}
function addBid() {
bidders.unshift(document.bidForm.bidId.value);
bids.unshift(document.bidForm.bidAmount.value);
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var timeText = hours + ":" + minutes + ":" + seconds;
bidTime.unshift(timeText);
writeBid();
}
function removeBid() {
bids.shift();
bidders.shift();
bidTime.shift();
writeBid();
}
as #nnnnnn said using += with your text variable works perfect:
JavaScript
var bids = [10, 20, 30];
var bidders = ['tim', 'sam', 'john'];
var bidTime = ['10/2/2013','12/5/213','14/1/2023'];
function writeBid() {
var historyText = " ";
for (var i = 0; i < bids.length; i++) {
historyText += bidTime[i] + " " + bids[i] + " " + bidders[i] + "\n";
document.bidForm.highBid.value = bids[i];
document.bidForm.bidId.value = " ";
document.bidForm.bidAmount.value = " ";
}
document.bidForm.bidList.value = historyText;
}
HTML
<form name="bidForm" id="bidForm">
<input type="text" name="bidId" id="bidId"/>
<input type="text" name="bidAmount" id="bidAmount"/>
<input type="text" name="highBid" id="highBid"/>
<textarea name="bidList" id="bidList"></textarea>
</form>