7

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/

goo
  • 2,060
  • 3
  • 27
  • 48

3 Answers3

21

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.

cfs
  • 10,172
  • 2
  • 28
  • 43
  • Still can't seem to get it to work. I've included a jsfiddle in my edit above – goo Aug 14 '13 at 19:58
  • @Jon I updated my answer with a new demo. There were two issues with the fiddle: one I had an extra `(` character and two jQuery wasn't included in the fiddle. – cfs Aug 14 '13 at 20:08
  • I should've noticed those. Thank you – goo Aug 14 '13 at 20:09
  • Still not working for me but since it's working fine in the jsfiddle, I'm assuming there's something going on in my code.. Thanks again – goo Aug 14 '13 at 20:13
  • @Jon double check your selectors and make sure you wrap your jQuery code with `$(function (){...}` – cfs Aug 14 '13 at 22:34
2

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";
    }
};
Colin Burr
  • 95
  • 7
1

The jQuery code you tried has an error, there should not be a right paren before 'click'

Colin Burr
  • 95
  • 7