How to set and get Boolean value from a asp.net hidden field
Asked Answered
T

2

6

I have a hidden field. Where I need to set a Boolean value intitially. After some operation I need to update the hidden filed value using JavaScript. But we can only store string value in hidden field. How to set/get Boolean value in hidden field?

Any Idea how to implement it?

Thermostat answered 5/1, 2015 at 8:31 Comment(1)
You need to parse or convert string to boolRefusal
O
8

As you correctly noticed - you can only store String in HiddenField Value. To determine boolean value in Code Behind - you should Convert String Value to Bool.

For example:

bool val = Convert.ToBoolean(HiddenField1.Value);

To set Hidden Field value:

HiddenField1.Value = val.ToString();

in JavaScript - you can accomplish this by using:

var hiddenFieldValueString = document.getElementById("HiddenField1").value;
var val = (hiddenFieldValueString === "true");

setting new Hidden Field Value:

document.getElementById("HiddenField1").value = val;
Overbold answered 5/1, 2015 at 8:47 Comment(1)
I know this is an old question but just ran into this issue, thanks @MikeW for the answer, I thinks is complete, the only thing I had to change is the comparison, should be compare to True instead of true, var val = (hiddenFieldValueString === "True");Dionnedionysia
M
0

You can use it without converting into Boolean

<asp:HiddenField ID="hf" runat="server" Value="True" />
<script type="text/javascript">
    var hf = document.getElementById('<%= hf.ClientID %>');
    if (hf.value == "True") {
        //your code
        hf.value == "False";
    } else {
        //your code
        hf.value == "True";
    }
</script>
Mcatee answered 5/1, 2015 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.