开发者

How to pass an anonymous array of strings to a JavaScript function?

I want to pass to an array of controls' IDs to a javascript script function so it will switch control's enable state.

For example, in C# it would be like this:

func(false, new[] { "Control1", "Control2", "Control3" });

In that function I want to find corresponding controls and disable/enable them. For one control I do this next way:

<script type="text/javascript" language="javascript">
    function switchControls(value, arr) {
        for (var n = 0; n < array.length; n++)
            document.getElementById([n]).disabled = value;
    }
</script>

<asp:CheckBox runat="server"
     onclick="switchControls(this.checked,
        [
            '<%= Control1.ClientID %>开发者_开发问答;',
            '<%= Control2.ClientID %>'
        ])" 
     Text="Take?" />

How to implement this properly? Have I to use jQuery?


No jQuery (or any other library) necessary.

It looks like your code will do the trick with a modification or two:

<script type="text/javascript">
    function switchControls(value, arr) {
        for (var n = 0; n < arr.length; n++){
            document.getElementById(arr[n]).disabled = value;
        }
    }
</script>  

As long as your ASP statement passes in a Boolean and an array of IDs (it looks like it does already, but I'm not familiar with ASP), it should work. For example, your onClick could call switchControls like this:

switchControls(true, ['foo','bar','baz']);


you don't "HAVE" to use jQuery, but it's somekind cooler to use it :)

function checkme(arr){
   if($.isArray(arr)){
     $.each(arr, function(){
       var currentState = this.attr('disabled');
       if(currentState == 'disabled' || currentState == 'true'){
          this.removeAttr('disabled');           
       }
       else{
          this.attr('disabled', 'disabled');
       }
     });
   }
}

usage: checkme([$("#someid"), $("#anotherid"), $("#anotherid")]);


<script type="text/javascript" language="javascript">
    function toggleControls(value) {
        $('.toggle').each(function() {
            if (value) {
                $(this).removeAttr('disabled');

            }
            else {
                $(this).attr('disabled', 'true');
            }
        });
    }
</script>

<asp:CheckBox runat="server" onclick="toggleControls(this.checked)" Text="Take?" />
<asp:TextBox runat="server" CssClass="toggle" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜