如何在文本框中输入值(嵌套在表单中的HTML表中)并将其传递给Javascript函数

How to enter a value in a textbox (nested in a HTML table which is in a form) and also pass it to a Javascript function

本文关键字:Javascript 表中 函数 输入 文本 表单 嵌套 HTML      更新时间:2023-09-26

我有一个JSP,访问一个bean的ArrayList来填充一个包含产品详细信息的HTML表。该表还显示了一个"Quantity"文本框,当用户填写时,应该将值传递给JS函数。JS函数依次计算产品的总价("Qty"*"Unit price")。我试图访问"数量"文本框并获得其值onChange,但我只得到null或未定义。我已经尝试了许多在线可用的解决方案(特别是SO),但这不起作用。如有任何帮助,我将不胜感激。

我的代码是这样的:

JS代码
<script type = "text/javascript">
    function calculateTotalPrice(tbval) {
 var t = tblContents.getElementsByTagName('qtyText')[0];
     alert("total qty is :" +t);
 var x = tblContents.getElementsByTagName('price')[0];
     alert("price is :" +x);
 var y = t*x;
 var h = tblContents.getElementsByTagName('totalPrice')[0];
 h.value = y;
alert("price set")
</script>
JSP代码
<table>
 <c:forEach items="${beanListInServlet1}" var= "exBean">
    <form action="ExampleServlet" method = "post" name = "tableForm">
       <input type="hidden" name="Id" value= "<c:out Value = "${exBean.Id}"/>"  />
<tr>         
      <td>
        <c:out Value = "${exBean.price}"/>            
      </td>
      <td>
        <input name = "qtyText" type = "textbox" size = "2"  defaultValue = "0" onChange         
          = "calculateTotalPrice()"/>
      </td>
      <td>
         <input name ="price" type = "hidden" value= "<c:out Value = "${exBean.price}"/>"  />
         <input name = "totalprice" type = "textbox" border = "0" size = "2" defaultValue    
           = "0" />          
      </td>
   </c:forEach>  
  </form>
</table>

你需要把这个传递给你的函数调用ala

 calculateTotalPrice(this)

 here is some addition info:

  function calculateTotalPrice(tbval) {
 myForm = document.forms[0];
 txtEntry = tbval.value;// or myForm.elements["name"].value
        alert("total qty is :" + txtEntry);
    var x = myForm.elements["price"].value
        alert("price is :" +x);
    var y = txtEntry*x;
    var h = tblContents.getElementsByTagName('totalPrice')[0];
  //  h.value = y;
  //  alert("price set")