1

I have four same UserControls inserted into Default.aspx. I want to write the data into HiddenField and write this data into Label1 using javascript.

The method only works for the last loaded UserControl - HiddenFieldLoader3.

Why the method does not work in all usercontrols? How can i fix my code?

Default.aspx

<%@ Register Src="~/HiddenFieldLoader.ascx" TagPrefix="uc1" TagName="HiddenFieldLoader" %>


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Default.aspx</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script src="HiddenFieldLoader.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <uc1:HiddenFieldLoader runat="server" ID="HiddenFieldLoader" />
        <uc1:HiddenFieldLoader runat="server" ID="HiddenFieldLoader1" />
        <uc1:HiddenFieldLoader runat="server" ID="HiddenFieldLoader2" />
        <uc1:HiddenFieldLoader runat="server" ID="HiddenFieldLoader3" />
    </form>
</body>
</html>

UserControl: HiddenFieldLoader.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HiddenFieldLoader.ascx.cs" Inherits="NewControls.HiddenFieldLoader" %>

<script type="text/javascript">
    HFLoader.declareVariables("<%=Button1.ClientID %>", "<%=HiddenField1.ClientID %>", "<%=Label1.ClientID %>");
</script>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:HiddenField ID="HiddenField1" runat="server" />

<input type="button" ID="Button1" value="Save" runat="server" />

<input type="button" ID="Button2" onclick="HFLoader.showEvent();" value="Show" runat="server" />

Javascript file: HiddenFieldLoader.js

HFLoader = {

    button: null,
    hiddenField: null,
    label: null,

    declareVariables: function (btn, hf, label) {
        HFLoader.button = btn;
        HFLoader.hiddenField = hf;
            HFLoader.label = label;
        },
        ///////SHOW EVENT
        showEvent: function () {
            $("#" + HFLoader.label).html($("#" + HFLoader.hiddenField).val());

        },
        //////!SHOW EVENT
        saveHiddenField: function (data) {

        $("#" + HFLoader.hiddenField).val(data);
    },

    buttons: function () {
        $("#" + HFLoader.button).click(function () {

            var datatest = "Data from button ID: " + $(this).attr("id");
            HFLoader.saveHiddenField(datatest);
            $("#" + HFLoader.label).html($("#" + HFLoader.hiddenField).val());
            return false;
        });
    },

    init: function () {
        $(function () {

            HFLoader.buttons();

        });
    }

};

HFLoader.init();

1 Answer 1

1

It doesn't work because you're using a single instance variable, HFLoader, and not an instance.

So one way to fix it is to wrap your HFLoader in a closer (function, local scope) so that the object is scoped per method call. In the example below, I wrapped the HFLoader variable in a creator function. Then, each call to HFLoaderCreator will produce a different version (instance) of the HFLoader object. The reason I chose to do it this way instead of creating a true JS class was because it required minimal code changes to demonstrate how it could be done.

Edit. Let's also say you want to recall the HFLoader at a later date to call on things, such as the saveHiddenField method. To do this, I've done 2 this. 1) I've added data('HFLoader') to the three elements passed in, so you can use any one of them to recall the HFLoader settings. And 2) I've added custom events that you can trigger to call the methods. These two options show two different ways that jQuery plugin developers use to allow access to underlying structures.

<script type="text/javascript">
    HFLoaderCreator("<%=Button1.ClientID %>", "<%=HiddenField1.ClientID %>", "<%=Label1.ClientID %>");
</script>


function HFLoaderCreator(btn, hf, label)
{
    var HFLoader = {

        button: null,
        hiddenField: null,
        label: null,

        declareVariables: function (btn, hf, label) {
            HFLoader.button = btn;
            HFLoader.hiddenField = hf;
            HFLoader.label = label;
        },

        saveHiddenField: function (data) {
            $("#" + HFLoader.hiddenField).val(data);
        },

        buttons: function () {
            $("#" + HFLoader.button).click(function () {

                var datatest = "Data from button ID: " + $(this).attr("id");
                HFLoader.saveHiddenField(datatest);
                $("#" + HFLoader.label).html($("#" + HFLoader.hiddenField).val());
                return false;
            });

            // add the data so it can be recalled at a later date
            $("#" + HFLoader.button).data('HFLoader', HFLoader);
            $("#" + HFLoader.hiddenField).data('HFLoader', HFLoader);
            $("#" + HFLoader.label).data('HFLoader', HFLoader);

            // add custom event handlers - saveHiddenField
            $("#" + HFLoader.button).on('saveHiddenField', HFLoader.saveHiddenField);
            $("#" + HFLoader.hiddenField).on('saveHiddenField', HFLoader.saveHiddenField);
            $("#" + HFLoader.label).on('saveHiddenField', HFLoader.saveHiddenField);

            // add custom event handlers - showEvent
            $("#" + HFLoader.button).on('showEvent', HFLoader.showEvent);
            $("#" + HFLoader.hiddenField).on('showEvent', HFLoader.showEvent);
            $("#" + HFLoader.label).on('showEvent', HFLoader.showEvent);  
        },

        init: function () {
            $(function () {

                HFLoader.buttons();

            });
        }

    };

   HFLoader.declareVariables(btn, hf, label);
   HFLoader.init();

   return HFLoader;
}

So now to make use of it all. In JS, if you wanted to look up the HFLoader data based on the Button1 ID, you might do something like this:

<script type="text/javascript">
  var HFLoader = $('#<%=Button1.ClientID %>').data('HFLoader');
  HFLoader.showEvent();
</script>

If you wanted to use ButtonID1 to trigger the custom event, which would ultimately call the showEvent method, you could do:

<script type="text/javascript">
  $('#<%=Button1.ClientID %>').trigger('showEvent');
</script>

And if you wanted to do it inline, like your first example...

<input type="button" ID="Button2" onclick="$('#<%=Button1.ClientID %>').data('HFLoader').showEvent();" value="Show" />

Although I'd highly recommend instead using JS to wire an event to Button2, such as:

$(function()
{
  $('#<%=Button2.ClientID').click(function()
  {
    $('#<%=Button1.ClientID %>').data('HFLoader').showEvent();

    return false;
  });
});

That way it's not inline script. Overall, the script for HFLoader is a bit hacked together. I'd recommend taking a look at the examples I've put together to extract the pieces of useful information and consider rethinking and/or rewriting the way you're doing things. Your brain is pushing you towards some kind of "global" view, or some kind of automatically scoped variable called HFLoader. But if you have 5 instances on a page, then you really want instances of some HFLoader object and not some global concept of HFLoader. It's like creating a new instance of a class instead of using a static or singleton instance of a class -- two very different concepts!

I hope this helps.

Sign up to request clarification or add additional context in comments.

3 Comments

I added a function to display the message - showEvent and button with ID - Button2. How can I change your method to call this fuction? Thank you!
I'm trying this "onclick="HFLoader.showEvent();"" and It doesn't work. How can i fix this? Thanks @Eli Gassert
Yes, that won't work. Because that variable doesn't exist at a top-level scope. See my edits. That's as much as I can possibly do to help you on your way. I typed this freehand, so please look out for typos. But the concepts are solid and it should get you on your way. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.