尝试通过javascript提交html表单变量时没有任何反应

Nothing happens when trying to submit html form variable via javascript

本文关键字:变量 任何反 表单 html javascript 提交      更新时间:2023-09-26

我是一个初学者javascript用户,我正在尝试让这个html表单传递给这个javascript函数并输出name变量,但是当我单击按钮提交时发生的一切是表单输入清除并且它停留在表单上而不是传递给javascript。

 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Life Insurance Calculator</title>

        <script type="text/javascript">
        var title = "Welcome to Life Insurance Co..!";
                    //Declaring  variable title             
        document.writeln(title.fontsize(8).fontcolor('red')); 
                   //Printing out the title on the page
        function Name(form){
        var customername = document.getElementByID("name").value;
        document.write(customername);
    }
    </script> 

</head>
 <body>

    <form name = "LifeCalcForm" action="" method="get">
    <p>To get a life insurance quote, please tell us about yourself.</p>
    <p><i>Note:only those under the age of 80 and non-smokers may apply</i></p>
    <p>Enter your name: <input type="text" name="name" /></p>

    <input type="submit" value="Calculate" onClick="Name(this.form)">
        </form>

  </body>
</html>
当您在

页面加载后(特别是在加载事件之后(执行document.write(customername);时,它将首先清除整个页面(包括脚本(并写入新内容。

而是执行以下操作:

alert(customername);

清除警报后(例如单击"确定"(,表单将提交,页面将重新加载。

顺便提一下,由于您在调用中传递了对函数的引用,并且窗体控件具有名称,因此可以使用:

alert(form.name.value);

请注意,窗体控件名称和 ID 用于创建窗体对象的属性,因此,名称为"name"的窗体控件将覆盖窗体自己的 name 属性(窗体还具有提交操作元素重置等属性(。因此,切勿使用可能与标准表单属性名称相同的控件名称,而应使用"用户名"等内容。

按照惯例,变量名称是为构造函数保留的,因此对普通函数使用小写。此外,函数是做事,所以通常最好使用一个动词来描述它的作用,例如

function getUserName(form) {
  return form.userName.value;
}

试试这个:

<html>
 <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>Life Insurance Calculator</title>

           <script type="text/javascript">
    var title = "Welcome to Life Insurance Co..!";
//    Declaring  variable title
    document.writeln(title.fontsize(8).fontcolor('red'));
//    Printing out the title on the page
    function Name(){
        var customername = document.getElementById("name").value;
        document.write(customername);
    }
</script>

    </head>
     <body>

        <form name = "LifeCalcForm" action="" method="get">
    <p>To get a life insurance quote, please tell us about yourself.</p>
    <p><i>Note:only those under the age of 80 and non-smokers may apply</i></p>
    <p>Enter your name: <input type="text" id="name" name="name" /></p>

    <input type="button" value="Calculate" onClick="Name()">
</form>

      </body>
    </html>