【问题标题】:Not able to read value entered in the form无法读取表单中输入的值
【发布时间】:2019-09-29 04:05:18
【问题描述】:

我是 Javascript 新手。我正在破解一个应用程序,其中我 需要从表单中获取值并对其进行处理:

  icode=document.forms[0].intcode;
        lamt=document.forms[0].lnamt.value;
        nom =document.forms[0].nomon.value;

并更新表单中其他字段的值,具体取决于 以上三个值是这样的:

document.forms[0].monpmt.value=Math.round(mamt);
            document.forms[0].totamt.value=totamt;

注意:这些值必须根据以上三个自动出现在表格中 用户输入的值。

function setTotamt() {
   icode=document.forms[0].intcode;
   lamt=document.forms[0].lnamt.value;
   nom =document.forms[0].nomon.value;
   intrate=icode.options[icode.selectedIndex].myvalue;
   if(lamt >0 && nom>0 && intrate>0) { 
     document.forms[0].monpmt.value=Math.round(mamt);
     document.forms[0].totamt.value=totamt;
   }
}

我在 Linux 平台和 tomcat 上执行此操作。

【问题讨论】:

  • jQuery 非常适合您。发布更多代码,我应该能够帮助您。
  • @RobG 无法获取表单中输入的值,请参见上面的代码..

标签: javascript serverside-javascript


【解决方案1】:
> icode=document.forms[0].intcode;
> lamt=document.forms[0].lnamt.value;
> nom =document.forms[0].nomon.value;

变量应该用 var 声明以保持它们本地化(假设上面的内容是在一个函数中)。语法或多或少是正确的,它建议的 HTML 结构如下:

<form ...>
  <input name="intcode" ... >
  <input name="lnamt" ... >
  <input name="nomon" ... >
  ...
  <input name="monpmt" ...>
  <input name="totamt" ...>
</form>

因此,如果您在表单中有一个按钮,它运行一个函数来获取一些值并更新一些其他控件的值,它可能看起来像:

  <input type="button" onclick="updateForm(this);" ...>

更新函数可能如下所示:

function updateForm(el) {
  var form = el.form; // store a reference to the form
  var icode = document.forms[0].intcode; // reference to element named "intcode"

  // Get the value of some controls
  var lamt = document.forms[0].lnamt.value;
  var nom = document.forms[0].nomon.value;

  // Do something with the values
  var mamt = ...;
  ...
  var totamt = ...;

  // Set some values in the form
  // Have a reference to the form so use it
  form.monpmt.value = Math.round(mamt);
  form.totamt.value = totamt;
}

请注意,表单控件的值始终是字符串,您应该测试获得的值以确保它们符合您的预期。如果您想在用户不按下按钮的情况下更新值[1],您可以使用 blur 事件来调用 updateForm。

您将需要验证输入值并处理错误(在用户填写所有字段之前进行更新,无效数据是显而易见的)。此外,您可能希望在放回数据时对其进行格式化,例如将数字格式化为两位小数。

  1. 最好有一个按钮,因为它可以是一个提交按钮,这样如果 javascript 被禁用或不工作,表单就会在服务器上提交和更新,并返回一个更新的表单。如果脚本可用,您可以取消提交并在客户端进行处理。如果需要,您可以更新模糊事件和按钮。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 2022-08-05
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多