0

这是选择多个和 JS 验证的问题:

<select name="service_ids[]" id="service_ids" size="7" multiple="">
    <option value="">-- Please Select --</option>
    <option value="1">S1</option>
    .
    .
    .
</select>

问题是,如果用户选择多个选项,包括第一个选项,那么以下操作将不起作用:

  1. document.getElementById('service_ids').selectedIndex => 0
  2. document.getElementById('service_ids').value => empty
4

1 回答 1

0

你可以这样解决

var services=document.getElementById('service_ids');

for(i=0;i<services.length;i++){
  if(services.opstions[i].selected&&sevices.optins[i].value=''){
    alert('This one should not be selected!');
    break; // or return false
  }
}

您可以将此代码放入在提交之前验证输入的函数中

更新

如果您只关心不应该选择第一个选项,您可以像这样检查它

if(document.getElementById('service_ids').options[0].selected){
     alert('This should not be selected');
}

如果您没有收到警报,您可以提交表单并在服务器端获取选定的值

于 2013-05-08T12:20:01.870 回答