问题
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.
回答1:
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.
回答2:
Move the variable assignment into the function, thus:
function terms() {
var checked = document.getElementById('checkbox').checked;
if (checked==false)
回答3:
Fixed in a fiddle - use the Event of clicking.
http://jsfiddle.net/hSMbf/1/
回答4:
Because checkboxes are not submitted in a form.submit() when they are unchecked I use a hidden field that gets updated when the checkbox is clicked on.
<input type="hidden" id="chbx" value="" name="0_">
<input type="checkbox" id="__chbx"
onclick="document.getElementById('chbx').value =
document.getElementById('__chbx').checked;"/>
(I have omitted the jsp-code that adds the checked
property to the checkbox-input if it was already checked when rendering the page.)
回答5:
Your variable checked
is set only once, so it always equals to the inital value. Move it inside your function terms()
.
回答6:
get the checked value inside your function
<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>
来源:https://stackoverflow.com/questions/6267758/how-do-i-use-javascript-to-change-value-of-a-hidden-input-depending-on-status-of