如何使用JavaScript将变量的值传递给文本区域?

时间:2014-05-22 21:37:40

标签: javascript html html5

继承我的代码: 如何使用JavaScript将变量的值传递给文本区域? 感谢大家的帮助!

var overtimeRate = 1.5;
var regularHours = prompt("How many regular hours?");  
var overtime = prompt("How many overtime hours?");


var hourRate = prompt("What is the hour rate of pay?");
var overtimeRatePerHour = hourRate * overtimeRate;
var pay = regularHours * hourRate;
var overtimePay = overtime * overtimeRatePerHour;

function calculator() {
document.write(pay);
document.write('<br>');
document.write(overtimePay);
document.write('<br>');
document.write(overtimePay + pay);
}

document.getElementById("textarea").value = calculator();

4 个答案:

答案 0 :(得分:0)

创建一个填充textarea的函数。

function myFunction() {
  var result = pay + '\n' + overtimePay + '\n' + (overtimePay + pay);
  document.getElementById("textarea").value = result;
}

然后在HTML中的按钮中的onclick事件上弹出它。

<button onclick="myFunction()">Click me</button>

答案 1 :(得分:0)

重写你的功能,如

function calculator() {
    var output = pay + '<br />' + overtimePay + '<br />' + (overtimePay + pay);
    return output;
}

你需要的是返回一个值的函数,然后可以把它放在textarea中。

答案 2 :(得分:0)

您的功能不应该打印(document.write)。它应该返回如下文本:

var overtimeRate = 1.5;
var regularHours = prompt("How many regular hours?");  
var overtime = prompt("How many overtime hours?");


var hourRate = prompt("What is the hour rate of pay?");
var overtimeRatePerHour = hourRate * overtimeRate;
var pay = regularHours * hourRate;
var overtimePay = overtime * overtimeRatePerHour;

function calculator() {
    var ret = '';
    ret = ret + pay
    ret = ret + '<br>'
    ret = ret + overtimePay
    ret = ret + '<br>'
    ret = ret + overtimePay + pay;
    return ret;
}

document.getElementById("textarea").value = calculator();

答案 3 :(得分:0)

使用onclick事件调用该函数。

<button onclick="myFunction()">Click Here</button>

Cyber​​Junkie刚回答,但好像他们删除了它。

或者,您可以将onchange事件与某些输入标记一起使用。这将使得每次改变其中一个输入时执行该功能。您可以使用document.getElementById(&#39; element_id&#39;)。而不是Javascript提示。

<form name="myForm"> Regular Hours: <input type="text" onchange="myFunction()" id="regHrs" value="0"> Overtime Hours:<input type="text" onchange="myFunction()" id="overHrs" value="0"> Pay Rate:<input type="text" onchange="myFunction()" id="rate" value="0"> </form>