How to change HTML Select when name is an array using Javascript

I have two html select objects with the same name (they are arrays with different indices).

What I'm trying to do is if "off" is selected from the select [0] element, I would like to disable the category [1] element. I'm trying to use document.getElementsByName (), but I haven't had any luck figuring out how to specifically set up the target array [1]. Below is a sample code.

<select name='category[0]'>
    <option value='0'>off</option>
    <option value='1'>on</option>
</select>

<select name='category[1]'></select>

      

My question is how do I change the properties of an HTML object that is an array? I realize I can easily do this using ID, but I would like to know how to do this using an array.

thank

+2


source to share


2 answers


Unverified:



<select name='category[0]'>
    <option value='0'>off</option>
    <option value='1'>on</option>
</select>

<select name='category[1]'></select>

<script>
var selects = document.getElementsByTagName('select');

for ( var i = 0, len = selects.length; i<l; ++i ) {
    if ( selects[i].name == 'category[1]' ) {
        // operate on selects[i];
        // you can also rely on getAttribute('name')
    }
}

</script>

      

+3


source


<select name='category[0]' onChange="disCat(this.value);">
    <option value='0'>off</option>
    <option value='1'>on</option>
</select>
<script type="text/javascript">
function disCat(val){
  if(val!="0") return;
  var sels=document.getElementsByTagName("select");
  for(i=0;i<sels.length;i++)
  {
    if(sels[i].getAttribute('name')=='category[1]') sels[i].disabled=true;
  }
}
</script>

      



+2


source







All Articles