首页 > 解决方案 > 在提交之前使用 JavaScript 更改 HTML 表单值

问题描述

使用外部 JavaScript 文件,我将下面这个按钮的值更改为“5”。
这行得通,我使用 console.log 检查该值是否确实更改为“5”。

<form action="getdata.php" method="POST">
  <button type="submit" class="firstHeavyGame button" name='storrage' value=''>PRESS THE BUTTON</button>
</form> 

然后,当单击此按钮时,它会将值发送到处理数据的 php 站点。
但是,我认为然后单击此按钮,该值将重置为“”“”(空白)。基本 HTML(我是新手)。
所以 php 脚本没有接收到任何数据。

我通过手动输入值来检查其他一切是否正常:

<form action="getdata.php" method="POST">
  <button type="submit" class="firstHeavyGame button" name='storrage' value='5'>PRESS THE BUTTON</button>
</form>

这可以正常工作(获取数字 5 并将其传递给处理它的 php 文件)。
现在我知道我犯了一个新手错误,但在进行研究时我似乎无法为我的例子找到答案。

希望你们能帮帮我!

标签: javascripthtml

解决方案


你可以试试:

<form action="getdata.php" method="POST" onSubmit="setValue(this)">
   <button type="submit" class="firstHeavyGame button" name='storrage' value=''>PRESS THE BUTTON</button>
</form> 
<script>
    function setValue(v) {
         v.storrage.value="5";
         return true;
     }
</script> 

推荐阅读