Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Toggle hidden field's value [closed]

Tags:

jquery

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/

like image 226
goo Avatar asked Aug 14 '13 19:08

goo


2 Answers

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.

like image 156
cfs Avatar answered Nov 10 '22 03:11

cfs


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";
    }
};
like image 28
Colin Burr Avatar answered Nov 10 '22 01:11

Colin Burr