简体   繁体   中英

Pass value from C# asp.net to JAVASCRIPT not working

I have a JS variable valuePercent that I get its value from hdnParam.Value (string that is obtained from C#) but its not working. I convert the string to an int using ParseInt() but I get NaN on my output. Any ideas?

.ASPX.cs

 string test = "67";

 hdnParam.Value = test;

.ASPX

  <%-- Hidden field to store string to be displayed in gage--%>
   <input type="hidden" id="hdnParam" runat="server" clientidmode="Static" />
   <script>
    var valuePercent = document.getElementById("hdnParam").value; 
    var gg1 = new JustGage({
        id: "gg1",
        donut: 0,
        title: "LAKELAND",
        titleFontColor: "#000000",
        min: 0,           
        max: 100,           
        labelFontColor: "#000000",
        humanFriendlyDecimal: 1,
        decimals: 1,
        symbol: "%",
        refreshAnimationType: "bounce",
        gaugeWidthScale: 0.6,
        customSectors: [{
            color: "#ff0000",
            lo: 0,
            hi: 79
        }, {
            color: "#ffa500",
            lo: 80,
            hi: 89
        }, {
            color: "#1eae1e",
            lo: 90,
            hi: 100
        }],
        counter: true
    });
    function refreshDiv() {
        gg1.refresh(parseInt(valuePercent)); //THIS DOES NOT WORK
        gg1.refresh(45); //THIS WORKS
    }

    var myVar = setInterval(function () { refreshDiv() }, 1000);
</script>

Set the value of the hidden field on Page_Load and call the javaScript function when OnClientClick event is fired.

MyPage.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    hiddenFieldValue.Value = "this is the value";
}

MarkUp :

<div>
    <asp:HiddenField ID="hiddenFieldValue" runat="server" />
    <asp:Button ID="ClickButton" runat="server" Text="Click Here" OnClientClick="DisplayValue()" />
</div>

javaScript :

function DisplayValue() {
        var valuePercent = document.getElementById("hiddenFieldValue").value;
        alert(valuePercent);
    }

Could you please check the generated id of "hidden input"? ASP.NET may add prefixes to id's, i see you've set the clientidmode=static but asking to be sure.

If id has prefix you may get it's value like that:

document.getElementById("<%= hdnParam.ClientID %>").value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM