0

我有一些代码有一个硬编码的联系人选择框,然后如果您单击添加按钮,它会添加更多联系人。可以从下拉列表中选择每个联系人,并在位置文本框中提供位置。

我希望在提交时能够知道他们是否选择了某人,如果没有,我想清除位置框,因为如果没有联系,就没有位置。

<!--- The myContactCount variable is set in another part of javascript this is the current count plus one of the number of current select boxes. --->

   <script type="text/javascript" language="javascript">
      var e='';
      var contactSelectedValue='';

      for(var i=1;1<myContactCount;i++){
         e = document.getElementById('myContactID_'+i);
         contactSelectedValue = e.options[e.selectedIndex].value;
         /* I am trying to alert the value so I can then use a if statement to check for null or even change the 'Select a Contact' value to 0 and test for that. */

        alert(contactSelectedValue);
     }
   </script>

   <!--- the ID will be 1-100 depending on how many contacts they have added --->

   <select name="myContactID_#ID#">
      <option value="">Select a Contact</option>
      <option value="1">Abe</option>
      <option value="2">Barbara</option>
      <option value="3">Cavlin</option>
   </select>

因此,在动态创建它们之后,它们的代码将如下所示。

<select name="myContactID_1">
   <option value="">Select a Contact</option>
   <option value="1">Abe</option>
   <option value="2">Barbara</option>
   <option value="3" selected="selected">Cavlin</option>
</select>

<select name="myContactID_2">
   <option value="">Select a Contact</option>
   <option value="1">Abe</option>
   <option value="2" selected="selected">Barbara</option>
   <option value="3">Cavlin</option>
</select>


<select name="myContactID_3">
   <option value="">Select a Contact</option>
   <option value="1" selected="selected">Abe</option>
   <option value="2">Barbara</option>
   <option value="3">Cavlin</option>
</select>
4

1 回答 1

1

您的脚本有几个问题:-

1<myContactCount而不是,i<=myContactCount您在选择中使用名称并尝试通过 id 获取它。

演示

html

<select id="myContactID_1">
   <option value="">Select a Contact</option>
   <option value="1">Abe</option>
   <option value="2">Barbara</option>
   <option value="3" selected="selected">Cavlin</option>
</select>

<select id="myContactID_2">
   <option value="">Select a Contact</option>
   <option value="1">Abe</option>
   <option value="2" selected="selected">Barbara</option>
   <option value="3">Cavlin</option>
</select>


<select id="myContactID_3">
   <option value="">Select a Contact</option>
   <option value="1" selected="selected">Abe</option>
   <option value="2">Barbara</option>
   <option value="3">Cavlin</option>
</select>

JS

 var e='';
      var contactSelectedValue='';

      for(var i=1;i<=3;i++){
         e = document.getElementById('myContactID_'+i);
         contactSelectedValue = e.options[e.selectedIndex].value;
         /* I am trying to alert the value so I can then use a if statement to check for null or even change the 'Select a Contact' value to 0 and test for that. */

        alert(contactSelectedValue);
     }
于 2013-05-13T14:44:51.917 回答