Devswa
Devswa

Reputation: 337

Delete duplicates in dropdown list

I have hard coded and added items to dropdownlist ie teamsize as 1,2,3 like that.

When i load this dropdownlist for edit/update i get duplicate values like this

1

1

2

3

4... How do i eliminate this duplicate values?

please find the code below

         <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>

Upvotes: 0

Views: 1493

Answers (2)

Ben Carey
Ben Carey

Reputation: 16948

If you do not want to use jQuery for this then I would advise placing all of the possible values into an array and looping through them in PHP. Then if the value exists, only place it once.

In addition, if you would like to use jQuery and the PHP is not possible in your circumstances then let me know and I will post up some jQuery.

UPDATE

This will do the trick. I have clearly laid out comments to explain what is going on step by step. Hope this helps.

Please note that it would be much more efficient to do this in 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;
    }
});

Upvotes: 1

vittore
vittore

Reputation: 17579

I suspect that line

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

add option which correspond to option choosen from select control, i e on first load you see coded list as this line returns empty option, but when you choose actual option this first one gets populated with choosen value

in this case you need to do 2 things 1 remove this line 2 add conditions to each line of hardcoded option and set it to select depending on the value of $event->proc_anesthesia_type and because of 2nd tank you will end up with 6 almost identical conditional statements putting selected='selected' to each option

so in order to make the overall code looks pretty i recomend instead of hardcodding options add values to list or even better dictionary and check this condition in a loop

Upvotes: 1

Related Questions