删除下拉列表中的重复项

时间:2012-02-02 23:51:54

标签: php javascript jquery html

我有硬编码并将项目添加到下拉列表中,即团队化为1,2,3这样。

当我加载此下拉列表进行编辑/更新时,我会得到像这样的重复值

1

1

2

3

4 ...如何消除此重复值?

请找到以下代码

         <select name="anesthesia" id="selectAnesthesiaVal" style="width:25%;" class="required safe" AppendDataBoundItems = "false">
          <option value="<?php echo isset($event)?$event->proc_anesthesia_type:"" ;?>"><?php echo isset($event)?$event->proc_anesthesia_type:"" ;?></option><option value="General">General</option>
          <option value="Mac">Mac</option>
          <option value="Spinal/Epidural">Spinal/Epidural</option>
          <option value="Regional">Regional</option>
          <option value="Local">Local</option>
          <option value="Other">Other</option>
        </select>

2 个答案:

答案 0 :(得分:1)

我怀疑那行

<option value="<?php echo isset($event)?$event->proc_anesthesia_type:"" ;?>"><?php echo isset($event)?$event->proc_anesthesia_type:"" ;?></option>

添加选项,对应于从选择控件中选择的选项,我首先加载你看到编码列表,因为这行返回空选项,但是当你选择实际选项时,第一个选项会填充选择值

在这种情况下你需要做两件事 1删除此行 2为每行硬编码选项添加条件,并根据$event->proc_anesthesia_type的值将其设置为选择 并且由于第二个坦克,你最终会得到6个几乎相同的条件语句,将selected='selected'放到每个选项

所以为了使整个代码看起来很漂亮我推荐而不是硬编码选项将值添加到列表甚至更好的字典并在循环中检查这个条件

答案 1 :(得分:1)

如果您不想为此使用jQuery,那么我建议将所有可能的值放入数组并在PHP中循环它们。然后,如果该值存在,则只放置一次。

另外,如果您想使用jQuery并且PHP在您的情况下是不可能的,请告诉我,我将发布一些jQuery。

<强>更新

这样就可以了。我已经清楚地提出了一些评论来解释一步一步的进展情况。希望这会有所帮助。

请注意,在PHP中执行此操作会更有效

// Set the present object
var present = {};
$('#selectAnesthesiaVal option').each(function(){
    // Get the text of the current option
    var text = $(this).text();
    // Test if the text is already present in the object
    if(present[text]){
        // If it is then remove it
        $(this).remove();
    }else{
        // Otherwise, place it in the object
        present[text] = true;
    }
});
相关问题