JSFiddle - React, Tailwind, and code Playground
by _sir
HTML
<p>Enter the stock prices for 5 consecutive days below:</p>
<p>Day 1:<input type="text" id="d1" value="0"></p>
<p>Day 2:<input type="text" id="d2" value="0"></p>
<p>Day 3:<input type="text" id="d3" value="0"></p>
<p>Day 4:<input type="text" id="d4" value="0"></p>
<p>Day 5:<input type="text" id="d5" value="0"></p>
<p><input type="button" value= "Show Span" id="span" class="consecutive" />
<input type="text" id="tots_amt"></p>
CSS
body {background-color:lightblue}
h1 {color:red}
p {color:black}
JavaScript
// Add a listener for the button click
document.getElementById('span').addEventListener('click',startAction);
function startAction() {
// Get the values and put them in an array
// only when you click the button
var price = [
parseInt(document.getElementById('d1').value),
parseInt(document.getElementById('d2').value),
parseInt(document.getElementById('d3').value),
parseInt(document.getElementById('d4').value),
parseInt(document.getElementById('d5').value)
];
// Call your function with the price data
var spanString = my_stock_span(price);
// Update the form field to show the value.
document.getElementById('tots_amt').value = spanString;
}
function my_stock_span (price){
var streak = [];
// Could also be defined with the values:
var streak = [1,1,1,1,1];
// Arrays start at zero
// you had 1 < 5, not i < 5
for (i = 0; i < 5; i++) {
// You set each to one, so you could just define the array
//streak[i] = 1;
for (var j = i - 1; j >=0 && price[i] >= price[j]; j--) {
streak[i]++;
}
}
var span = "";
// We can replace this loop with a join
/*
for (var k=0; k<5; k++) {
span = span + streak[k];
}
*/
span = streak.join();
return span;
}