【问题标题】:How to insert a string to a text field programatically in javascript如何在javascript中以编程方式将字符串插入文本字段
【发布时间】:2012-08-12 22:28:11
【问题描述】:

我想使用 javascript 将文本字符串添加到文本字段,但我不想使用 onClick 或 onLoad 事件来执行此操作。

我只是希望 javascript 在浏览器读取后立即执行,并且 javascript 将位于 html 的正文中。

文本字段类似于

<form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>

我尝试过类似的方法,但它不起作用:

<script type="text/javascript"> edit-form.value="the new value"; </script>

我该怎么做?

【问题讨论】:

    标签: javascript javascript-events


    【解决方案1】:

    你有没有尝试通过document.getElementById()得到这个

    <script type="text/javascript"> document.getElementById("edit-mail").value="the new value"; </script>
    

    假设 edit-mail 是您的文本框 ID

    【讨论】:

      【解决方案2】:

      试试

      document.getElementById("edit-mail").value="he new value"
      

      【讨论】:

        【解决方案3】:

        很多时候,您无法享受所有具有 id 的表单元素。这就是如何使它与只有 name 属性的字段一起工作:

        document.getElementById('user-registration-form').elements['edit-form'].value = 'new value';
        

        【讨论】:

          【解决方案4】:
          var textfield = document.getElementByName("x");
          textfield.value = "My text";
          

          或直接document.getElementByName("x").value = "My text";

          如果您想根据元素的 id 而不是名称来获取元素,则可以使用 getElementById 而不是使用 getElementByName。

          【讨论】:

            【解决方案5】:

            【讨论】:

            • 我已经调整了我认为是错字的答案。希望你不要介意。
            猜你喜欢
            • 2013-07-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多