简体   繁体   English

单击按钮时更新文本框值

[英]Update textbox value when a button is clicked

Here is my problem, when i click the submit button, the textbox doesn't show any value Is there any mistakes, i am just a newbie Thank you very much 这是我的问题,当我单击“提交”按钮时,文本框没有显示任何值是否有任何错误,我只是一个新手。非常感谢

    <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>

The first issue is that you're using the same name for the element as the function , so window.setValue is not the function, but the submit button, and that's an error. 第一个问题是, 您使用的元素名称与function相同 ,因此window.setValue不是函数,而是Submit按钮,这是一个错误。

The second issue is that when you hit the submit button, the form is submitted and the page reloads, that's why you wont see a value, you have to prevent the form from submitting. 第二个问题是,当您单击“ 提交”按钮时,将提交表单并重新加载页面,这就是为什么您看不到值的原因,因此必须阻止表单提交。

You could do it with javascript, but the easiest would be to just use a regular button instead of the submit button. 您可以使用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 小提琴

I was typing the same answer what Adeneo just given, thank you Adeneo. 我输入的答案与Adeneo刚才给出的相同,谢谢Adeneo。 And user3635102, your <form> was good, you can keep it as it was. 和user3635102一样,您的<form>很好,您可以保持原样。 Only you need to change <input type="submit"> to <input type="button"> . 只有您需要将<input type="submit">更改为<input type="button"> if you need to submit the form in future you can update your Javascript as follows which will submit form1: 如果您以后需要提交表单,则可以按以下方式更新Javascript,从而提交form1:

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

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

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