Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Javascript to change value of a hidden input depending on status of a checkbox?

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.

like image 594
Dave Avatar asked Jun 07 '11 15:06

Dave


People also ask

Can JavaScript read hidden field value?

In JavaScript, you can use following two ways to get hidden field value in a form : document. getElementById('hidden field id'). value.

How do you assign a value to a hidden field?

In jQuery to set a hidden field value, we use . val() method. The jQuery . val() method is used to get or set the values of form elements such as input, select, textarea.

Can change value in input JavaScript?

Change the Input Value Using the setAttribute() Function in JavaScript. We can also use the setAttribute() function instead of the value property to set the input value. We can also use the forms() function instead of the getElementById() or querySelector() function to get the element using the form name and input name ...


2 Answers

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.

This jsFiddle shows a working example.

like image 68
maerics Avatar answered Sep 16 '22 21:09

maerics


Move the variable assignment into the function, thus:

function terms() {
    var checked = document.getElementById('checkbox').checked;
    if (checked==false)
like image 37
stuartd Avatar answered Sep 19 '22 21:09

stuartd