John John - 1 month ago 7
Javascript Question

How do I add multiple values to a textarea in Javascript?

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();
}

Answer

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>
Comments