JQuery: toggle hidden field value

I’ve been looking for how to do this for some time. In my form, I would like to switch the value back and forth (true ↔ false) by clicking the div.

How do you switch true / false using jQuery?


<input id="myHiddenField" name="my[hidden_field]" type="hidden" value="false"> <a id="myDiv">Click Me</a> 

I 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/

+4
source share
3 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 did not post your markup, so I used some placeholder identifiers. You will need to update them for selectors working 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 they will not be true Boolean.

+14
source

Only with 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"; } }; 
+2
source

The jQuery code you tried has an error, there should not be a valid character before the 'click'

0
source

Source: https://habr.com/ru/post/1497108/


All Articles