dependent dropdown with jquery CODEIGNITER previous selection does not go away

时间:2016-06-06 14:18:46

标签: javascript php jquery codeigniter

I have this dependent dropdown working initially, but after the second selection the values of the first selection do not go away. Instead, the new values are just mixed with the previous values. I'm not familiar with jQuery but I need to finish this one as soon as possible.

first dropdown

@RestController

public class MessageService {

    @Autowired
    MessageModel messageModel;

    @RequestMapping(value="/message",method=RequestMethod.POST)
    public Message save(@RequestBody Message message) {
        return messageModel.save(message);
    }

    @PreAuthorize("permitAll()")
    @RequestMapping(value="/messagee",method=RequestMethod.POST)
    public Message savee(@RequestBody Message message) {
        System.out.println("hjgjhghggfhgf");
        return messageModel.savee(message);
    }
}

second dropdown

            <select class="form-control" name = "PROV_ID" id = "PROV_ID">
              <option></option>
                <?php foreach ($content as $cs) {?>
                  <option value="<?php echo $cs->PROV_ID; ?>"><?php echo $cs->PROVINCE; ?></option>
                <?php } ?> 
            </select>

jquery

            <select name = 'CT_ID' id = 'CT_ID'>
                <option value="">-- Select Type --</option>
            </select>

I want to refresh the value of the second dropdown whenever I select a new option on the first dropdown.

2 个答案:

答案 0 :(得分:0)

在追加之前清除现有选项:

success: function(data){
    var select = $('#CT_ID');
    select.empty();
    $.each(data, function(i, option){
        select.append("<option value='"+option.CT_ID+"'>"+option.CITY+"</option>");
    });
}

答案 1 :(得分:0)

这是因为您使用append将HTML添加到select元素。我建议使用jQuery的html来设置select的HTML(这将清除任何现有的选项元素)。这里的额外好处是你只做一个DOM操作,而不是每个选项一个。

success: function(data){
    var $select = $('#CT_ID'),
      html = '';
    $.each(data, function(i, option) {
        html += "<option value='"+option.CT_ID+"'>"+option.CITY+"</option>";
    });
    $select.html(html);
}