通过javascript编辑html输入表单的值 [英] Edit value of a html input form by javascript

查看:63
本文介绍了通过javascript编辑html输入表单的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML代码:

<form action="Generator.klx" method="post" onsubmit="genarate('hiddenField')">
   <input type="hidden" id="hiddenField" name="hidden" value=""/>
   <input type="submit" name="submit"/>
</form>

我的JavaScript:

my JavaScript:

function genarate(hiddenField){
  var field = document.getElementById(hiddenField);
  field.value = "new Value";
 }

但是它只是没有用:(.有人可以告诉我我错了吗?
谢谢

But it just didnot work :(. Can anybody tell me where I was wrong?
Thank you

推荐答案

您引用的代码应该可以正常工作,并且在我使用各种浏览器进行的测试中都可以.(我已经在本地以POSTed形式尝试过,但是您也可以在这里尝试: http://jsbin.com/ehoro4/1 我已将方法更改为 GET ,以便您可以在URL中查看结果.)

Your code as quoted should be working, and does in my tests with a variety of browsers. (I've tried it locally, with a POSTed form, but you can also try it here: http://jsbin.com/ehoro4/1 I've changed the method to GET so you can see the result in the URL.)

我的猜测是您的页面上还有 else 内容,其中包含 name id "hiddenField",而不仅仅是隐藏字段你已经引用了.如果您将该字段的名称更改为"fluglehorn"或页面上其他位置不太可能使用的(um)名称,则可能会很好.这是因为 getElementById 使用的命名空间(非常)非常拥挤.

My guess is that you have something else on the page with the name or id "hiddenField", other than just the hidden field you've quoted. If you change the name of the field to "fluglehorn" or something else that's (um) unlikely to be elsewhere on your page, it may well work. That's because the namespace used by getElementById is (sadly) quite crowded.

或者,您确定 genarate 是否出现在全局范围内?(例如,它在所有其他函数的外部.)因为您的 onsubmit 属性要求 genarate 是全局的.这样就可以了:

Alternately, are you sure that genarate is appearing at global scope? (E.g., it's outside of all other functions.) Because your onsubmit attribute requires that genarate be global. So this works:

<form action="#" method="get" onsubmit="genarate('hiddenField')">
   <input type="hidden" id="hiddenField" name="hidden" value=""/>
   <input type="submit" name="submit"/>
</form>
<script>
function genarate(hiddenField){
  var field = document.getElementById(hiddenField);
  field.value = "new Value";
}
</script>

但是例如,这不会:

<form action="#" method="get" onsubmit="genarate('hiddenField')">
   <input type="hidden" id="hiddenField" name="hidden" value=""/>
   <input type="submit" name="submit"/>
</form>
<script>
(function() { // Begin scoping function to avoid global symbols (not uncommon)
    function genarate(hiddenField){
      var field = document.getElementById(hiddenField);
      field.value = "new Value";
    }
})();
</script>

还建议使用调试器(由于没有任何借口客户端调试器在2011年发布)在 genarate 函数上设置一个断点,然后逐步进行操作,以了解发生了什么问题.

Also recommend using a debugger (there's no excuse for not using client-side debuggers here in 2011) to set a breakpoint on the genarate function and walk through, to see what's going wrong.

这篇关于通过javascript编辑html输入表单的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆