如何使用Javascript更改隐藏输入的值取决于复选框的状态? [英] How do I use Javascript to change value of a hidden input depending on status of a checkbox?

查看:144
本文介绍了如何使用Javascript更改隐藏输入的值取决于复选框的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据复选框的值更改隐藏的输入字段的值。我不太了解Javascript,但这是我迄今为止。

I am trying to change the value of a hidden input field, depending on the value of a checkbox. I don't know much about Javascript but this is what I have so far.

<input type="hidden" value="" id="delterms" name="O_" />
<input type="checkbox" id="checkbox" onchange="terms()" />
<script type="text/javascript">
 var checked = document.getElementById('checkbox').checked;
  function terms() {
   if (checked==false)
    {
     document.getElementById('delterms').value=''
    }
   else
    {
    document.getElementById('delterms').value='Accepted'
    }
}
</script>

我得到它的工作,但只有在第一次点击,有无论如何设置的值,复选框状态?

I got it to work but only on the first click, is there anyway to set the value depending on the checkbox status? I suspect there is some far simpler way and I am no doubt over complicating the issue.

推荐答案

尝试添加事件监听器,而不是使用HTMLonchange属性,这可能澄清你的事情,并可能使您的代码更容易维护长期:

Try adding an event listener instead of using the HTML "onchange" attribute, this might clarify things for you and will probably make your code easier to maintain in the long run:

<input type="hidden" id="delterms" value="" name="O_" />
<input type="checkbox" id="checkbox" />
<script type="text/javascript">
  var checkbox = document.getElementById('checkbox')
    , hidden = document.getElementById('delterms');
  checkbox.addEventListener('change', function() {
    hidden.value = (this.checked) ? 'Accepted' : '';
  }, false);
</script>

想法是每当用户单击复选框时运行匿名函数,

The idea is that the anonymous function gets run every time the user clicks the checkbox, which sets the value of the hidden field to either "Accepted" or the empty string, depending on whether or not the box is checked.

这个 jsFiddle 显示了一个工作示例。

This jsFiddle shows a working example.

这篇关于如何使用Javascript更改隐藏输入的值取决于复选框的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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