将值从函数传递到输入字段

Passing value from a function into a input field

本文关键字:输入 字段 函数      更新时间:2024-05-16

问题:我试图将函数的返回值传递到输入字段。

我没有错误,字段只是空白。

问题:为什么我的代码不起作用?

HTML

<tr>
<td>Quantity to be dredged</td>
<td><input type="number"  class="" id="shorePipe"></input></td>
</tr>

JavaScript

var shorePipe = function() {
  var val = 100;
  var val2 = 100;
  var total = val * val2 / 100;
  // return total;
  document.getElementById('shorePipe').value = total;
};

提前感谢!

由于您的代码运行良好(除了</input>之外),我在这里看到的唯一问题是,一旦读取并准备好DOM,您可能就不会调用shorePipe();

jsBin演示

所以把你的JS放在关闭</body>标签之前

<script>
var shorePipe = function() {
  var val = 100;
  var val2 = 100;
  var total = val * val2 / 100;
  // return total;
  document.getElementById('shorePipe').value = total;
};
shorePipe();
</script>
</body>

还要注意CCD_ 4是无效的。<input>位于void元素组中,不应具有结束标记。

您必须调用函数

shorePipe();

这是一把小提琴:https://jsfiddle.net/2vxdyvgz/

  1. 输入不需要自行关闭
  2. 确保你真的在某个地方调用了JS函数

我为您创建了这个JSFiddle:https://jsfiddle.net/pd12edbp/2/

<input type="number"  class="" id="shorePipe" readyonly>

JS:

var shorePipe = function() {
   var val = 100;
   var val2 = 100;
   var total = val * val2 / 100;
   // return total;
   document.getElementById('shorePipe').value = total;
};
$(document).ready(function(){
    shorePipe();
});

在您的原始帖子中,您将值传递给ID为shorePipe的元素,并且您的输入具有ID avgSubPipe

元素ID必须匹配。ANd,你必须启动功能

HTML

<tr>
<td>Quantity to be dredged</td>
<td><input type="number"  class="" id="avgSubPipe" readonly ></td>
</tr>

和Javascript:

var shorePipe = function() {
  var val = 100;
  var val2 = 100;
  var total = val * val2 / 100;
  // return total;
  document.getElementById('shorePipe').value = total;
};
// calling function
shorePipe();

https://jsfiddle.net/yhz7syhs/1/