繁体   English   中英

window.alert() 不显示输入

[英]window.alert() not displaying the input

我对 html 和学习它还是新手。 现在我的问题是它不会显示我的输入,我相信我的代码做得非常正确,但我可能是错的。 我不确定它有什么问题。 先感谢您!

<html>
<head>
    <title>OVERSEAS VISITATION</title>
    
     <style>
        
        table, th, td {
           border: 1px solid black;
        }
     </style>
</head>
<body>
<form>
    <table>
        <tr>
            <th colspan="2">
            v. oversea visit
            </th>
        </tr>
        <tr>
            <td>
                <b> Student activities (overseas))</b> Max RM6000 :
            </td>
             <td>
                 <input type="text" name="visit">
             </td>
        </tr>
    </table>
    <br><br>
    <input type="Submit" value="Submit" onsubmit="printOutput()">
</form>
<script> 
        
        function printOutput(){
            var rm = document.getElementByName('visit');
            window.alert("RM :"+visit);
        }
</script>
</body>
</html>

您的代码中有一些问题:

  1. 由于按钮的类型是提交,因此表单正在提交并且您正在丢失当前页面。
  2. getElementByName不正确,您缺少s ,应该是getElementsByName 它返回集合,你必须使用正确的index 不过,我更喜欢使用querySelector() 此外,您必须从元素中获取value
  3. 您没有使用rm的值显示在警报中,而是使用了导致错误的访问

试试下面的方法:

 <html> <head> <title>OVERSEAS VISITATION</title> <style> table, th, td { border: 1px solid black; } </style> </head> <body> <form> <table> <tr> <th colspan="2"> v. oversea visit </th> </tr> <tr> <td> <b> Student activities (overseas))</b> Max RM6000: </td> <td> <input type="text" name="visit"> </td> </tr> </table> <br><br> <input type="button" value="Submit" onclick="printOutput()"> </form> <script> function printOutput(){ var rm = document.querySelector('[name=visit]').value; window.alert("RM:"+rm); } </script> </body> </html>

更正的代码:

<form onsubmit="printOutput()">
    <table>
        <tr>
            <th colspan="2">
                v. oversea visit
            </th>
        </tr>
        <tr>
            <td>
                <b> Student activities (overseas))</b> Max RM6000 :
            </td>
            <td>
                <input type="text" name="visit">
            </td>
        </tr>
    </table>
    <br><br>
    <input type="Submit" value="Submit">
</form>
<script>

    function printOutput(){
        var rm = document.getElementsByName('visit');
        window.alert("RM :"+ rm[0].value);
    }
</script>

您必须在代码中修复的三件事:

  1. onsubmit 方法是在表单上定义的,而不是在提交输入上。
  2. getElementByName 不是 function,function 是 getElementsByName,它返回具有搜索名称属性的所有元素的数组。
  3. 您必须找到输入的.value 才能获得输入中输入的值。

更改输入类型提交到按钮并在 javascript 使用值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM