How to use Javascript to change the value of hidden input depending on the status of the checkbox?

I am trying to change the value of a hidden input field, depending on the value of the checkbox. I am not very good at Javascript, but this is what I still have.

<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, anyway, to set the value depending on the status of the checkbox? I suspect there is a much simpler way, and I will no doubt complicate the problem.

+5
source share
6 answers

HTML "onchange", , , :

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

, , , "", , .

jsFiddle .

+5

, :

function terms() {
    var checked = document.getElementById('checkbox').checked;
    if (checked==false)
+1

checked , . terms().

0

    <script type="text/javascript">

      function terms() {
       var checked = document.getElementById('checkbox').checked;
       if (checked==false)
        {
         document.getElementById('delterms').value=''
        }
       else
        {
        document.getElementById('delterms').value='Accepted'
        }
    }
    </script>
0

form.submit(), , , .

<input type="hidden" id="chbx" value="" name="0_">
<input type="checkbox" id="__chbx" 
    onclick="document.getElementById('chbx').value = 
             document.getElementById('__chbx').checked;"/>

( jsp-, checked , .)

0

All Articles