javascript - 需要在两种表单的字段上使用javascript函数

标签 javascript html forms

嘿,我需要使用java脚本函数来验证两种表单的字段。 基本上,标准是当用户选择表单名称时,要求字段必须在下一个表单上可见。我需要询问是否可以对不同页面上的表单使用java脚本函数。下面是我的代码

rpt 表单代码

<html>
<head>
<script type="text/javascript" src="javascript/formvalidations.js"></script>
</head>
<form name="rpt" method="post" action="">
    <label>Form Name </label>
    <select id="formname" name="formname"> 
    <option value="" selected="selected">--Please Select Form Name--</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select><br />
<input id="ok" type="submit" name="ok" value="OK" onclick="return chkform();" />
</form>
</html>

java脚本函数代码

function chkform(){
    var formname = document.forms.rpt.formname.value;
        if (formname == "1"){
            document.forms.reportform.getElementById("1").style.display="inline";
            document.forms.reportform.getElementById("2").style.display="inline";
            document.forms.reportform.getElementById("3").style.display="inline"
            document.forms.reportform.getElementById("4").style.display="none";
            document.forms.reportform.getElementById("5").style.display="none";

        }
        elseif (formname == "2"){
            document.forms.reportform.getElementById("1").style.display="inline";
            document.forms.reportform.getElementById("2").style.display="none";
            document.forms.reportform.getElementById("3").style.display="inline"
            document.forms.reportform.getElementById("4").style.display="none";
            document.forms.reportform.getElementById("5").style.display="inline";
        }
        else{
            alert("select form name");
            return false;
        }
}

我的报表有 5 个字段。我需要必填字段在报告表单中可见。假设如果用户在 rpt 中选择值 1,则字段 1、2 和 3 必须可见。

最佳答案

此行有语法错误:

elseif (formname == "2"){

JavaScript 没有 elseif 作为单个单词,您需要插入一个空格:

else if (formname == "2"){

此外,getElementById() functiondocument 的方法,而不是单个 html 元素的方法,因此使用:

document.getElementById("1").style.display="inline";
// and so forth

如果您使用浏览器的 JS 控制台(例如,在 Chrome 中按 F12),它会向您报告这些错误(它不会告诉您如何修复它们,但至少会为您指明正确的方向) 。

关于javascript - 需要在两种表单的字段上使用javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14495970/

相关文章:

javascript - 如何将 React Hooks 与 video.js 一起使用?

PHP 如果存在多个变量

javascript - 选择单选按钮时,如何测试是否已选择另一个单选按钮?

javascript - 使用 jquery、froogaloog 和 wordpress 控制 Vimeo iframe 时遇到问题

javascript - 如何根据 Vue 中的 select 更改输入的占位符

javascript - Ionic 2/3 - 如何在屏幕较宽时查看 2 张幻灯片?

html - 在 HTML5 日期时间本地输入中设置默认值时出现“无效值”

forms - 当 AngularJS 表单无效时禁用提交按钮

javascript - 在 JavaScript 中引用操作字段

javascript - 按下某个键时添加\到一个字符串