找不到我想要的东西,但是如果我错过了明显的东西,对不起。我基本上是想让JavaScript函数在提交表单然后将其输入数据库之前,检查多个选择框是否具有唯一值。

可以有任意数量的选择框,但是所有选择框都遵循类似的命名格式,形式为:

operator_address_type_0
operator_address_type_1
operator_address_type_2
etc.


我只是想知道如何设置JavaScript函数以遍历所有选择框,并警告用户并停止提交(如果发现具有相同值的话)。

谢谢你的帮助。

编辑:

这是我当前选择框的一些简化HTML。我不得不简化它很多,因为它们所在的表都是通过查询数据库通过AJAX加载的。

<select name="operator_address_type_0">
<option value="Main">Main</option>
<option value="Payment">Payment</option>
<option value="Poster">Poster</option>
</select>

<select name="operator_address_type_1">
<option value="Main">Main</option>
<option value="Payment">Payment</option>
<option value="Poster">Poster</option>
</select>


就像这样,但将来可能会有更多选择,我只想检查一下是否只有一个主要地址,一个付款地址,一个发帖人地址等。

最佳答案

类似于以下内容?

function checkDuplicates() {
  var selects = document.getElementsByTagName("select"),
      i,
      current,
      selected = {};
  for(i = 0; i < selects.length; i++){
    current = selects[i].selectedIndex;
    if (selected[current]) {
      alert("Each address type may not be selected more than once.");
      return false;
    } else
      selected[current] = true;
  }
  return true;
}


演示:http://jsfiddle.net/GKTYE/

这将遍历选择并记录每个选择的索引,如果发现重复则停止。假设所有选择都具有相同顺序的相同选项。要测试实际选择的值:

 current = selects[i].options[selects[i].selectedIndex].value;

07-24 09:44
查看更多