javascript - 单击按钮时更新文本框值

标签 javascript html

这是我的问题,当我点击提交按钮时,文本框没有显示任何值 有没有错误,我是新手 非常感谢

    <form id="form1" name="form1" method="post" >

      <p>
        <input type="submit" name="setValue" id="setValue" value="submit" onclick="setValue()"/>
      </p>
      <p>
        <label>
          <input type="text" name="bbb" id="bbb" />
        </label>
       </p>
    </form>

    <script type="text/javascript">
    function setValue()
    {
        document.getElementById('bbb').value="new value here";
    }
      </script>

最佳答案

第一个问题是您为元素使用了与函数相同的名称,因此window.setValue 不是函数,而是提交按钮,这是一个错误。

第二个问题是当您点击提交 按钮时,表单被提交并且页面重新加载,这就是您看不到值的原因,您必须阻止提交的表单。

您可以使用 javascript 来完成,但最简单的方法是使用常规按钮而不是提交按钮。

<form id="form1" name="form1" method="post">
    <p>
        <input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
    </p>
    <p>
        <label>
            <input type="text" name="bbb" id="bbb" />
        </label>
    </p>
</form>
<script type="text/javascript">
    function setValue() {
        document.getElementById('bbb').value = "new value here";
    }
</script>

FIDDLE

关于javascript - 单击按钮时更新文本框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23798989/

相关文章:

html - 子列表父级中的 CSS 菜单布局

javascript - 当元素到达页面顶部时淡入淡出?

javascript - (Vue 和 Firebase)我在一个数组中保存多个图像时遇到问题

javascript - 使用 for 循环从 Javascript 函数返回多个值

javascript - 从 ViewModel 外部调用 Knockout 函数

html - 沿 SVG 路径渲染 RTL 文本

javascript - 提示不适用于 php 页面

javascript - 适用于许多图像及其调色板的算法

javascript - 如何计算 HTML 表格中*可见*行的数量?

html - 媒体查询的绝对定位