I've been searching for a while now on how to do this. In my form, I would like to toggle a value back and forth (true <-> false) by click a div.
How do you toggle a hidden field's true/false value using jquery?
<input id="myHiddenField" name="my[hidden_field]" type="hidden" value="false">
<a id="myDiv">Click Me</a>
I've tried
$('#myDiv').on('click'), (function() {
var hiddenField = $('#myHiddenField'),
val = hiddenField.val();
hiddenField.val(val === "true" ? "false" : "true");
});
but nothing :(
jsfiddle: http://jsfiddle.net/MV3A4/2/
This is pretty straight forward. Add a click handler to your div, and update the value of your input using the val() method.
You haven't posted your markup, so I've used some placeholder ID's. You'll need to update those to selectors that work in your context:
Working Demo
$('#myDiv').on('click', function() {
var hiddenField = $('#myHiddenField'),
val = hiddenField.val();
hiddenField.val(val === "true" ? "false" : "true");
});
Note that input values are always strings, so these won't be true booleans.
With just javascript:
document.getElementById('myClickableDiv').addEventListener('click',function(){
var value =document.getElementById('myHiddenField').value();
if(value === "true"){
document.getElementById('myHiddenField').value = "false";
}else{
document.getElementById('myHiddenField').value = "true";
}
};
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