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.
In JavaScript, you can use following two ways to get hidden field value in a form : document. getElementById('hidden field id'). value.
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.
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 ...
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.
Move the variable assignment into the function, thus:
function terms() {
var checked = document.getElementById('checkbox').checked;
if (checked==false)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With