简体   繁体   中英

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" />

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