views:

114

answers:

2

I have an asp.net codebehind page linking several checkboxes to javascript methods. I want to make only one javascript method to handle them all since they are the same logic, how would i do this?

code behind page load:

checkBoxShowPrices.Attributes.Add("onclick", "return checkBoxShowPrices_click(event);");

checkBoxShowInventory.Attributes.Add("onclick", "return checkBoxShowInventory_click(event);");

aspx page javascript; obviously they all do the same thing for their assigned checkbox, but i'm thinking this can be reduced to one method:

function checkBoxShowPrices_click(e)
{

    if (_hasChanged)

    {

    confirm('All changes will be lost. Do you wish to continue?', function(arg)

    {

        if (arg.toUpperCase() == 'YES')

        {
     var checkBox = document.getElementById('<%=checkBoxShowPrices.UniqueID%
>');
     checkBox.checked = !checkBox.checked;

     eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");

     _hasChanged = false;

        }

    });

    return false;

    }

    else

    {

    eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");

    }

}



function checkBoxShowInventory_click(e)

{

    if (_hasChanged)

    {

    confirm('All changes will be lost. Do you wish to continue?', function(arg)

    {

        if (arg.toUpperCase() == 'YES')

        {

     var checkBox = document.getElementById('<%
=checkBoxShowInventory.UniqueID%>');

     checkBox.checked = !checkBox.checked;

     eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");

     _hasChanged = false;

        }

    });

    return false;

    }

    else

    {

    eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");

    }

}
A: 

You can always write a function that returns a function:

function genF(x, y) {
    return function(z) { return x+y*z; };
};

var f1 = genF(1,2);
var f2 = genF(2,3);

f1(5);
f2(5);

That might help in your case, I think. (Your code-paste is hard to read..)

Marcus Lindblom
+2  A: 

Add to the event the checkbox that is raising it:

checkBoxShoPrices.Attributes.Add("onclick", "return checkBox_click(this, event);");

Afterwards in the function you declare it like this:

function checkBoxShowPrices_click(checkbox, e){ ...}

and you have in checkbox the instance you need

antonioh