添加新项目后重新填充选择菜单

时间:2012-12-17 21:28:57

标签: php ajax jquery

我环顾四周,却看不到任何符合我需求的东西。基本上我尝试在添加项目后刷新选择菜单(而不是整个页面)。我目前有一个ajax查询,允许用户添加一个新的文件夹,它完美地工作。添加后,我希望将该文件夹选项添加到选择菜单中。以下是我的代码:

HTML:

<form>
<select id="basic-combo" name="basic-combo" size="1" onchange="showFolders(this.value)">
  <?php
     foreach ($folder as $t)
     {
       echo '<option value="'.$t['folder_id'].'">'.$t['name'].'</option>';
     }
   ?>  
 </select>
 </form>

 // This is the popup form to add a new folder
 <div style="float:right; margin-top:10px;">
        <div class="messagepop pop">
            <form method="post" id="new_folder" >
                <p><label for="folder">Folder Name</label><input type="text" size="20" maxlength="13" name="folder_name" id="folder_name" /></p>
                <p><input type="submit" value="Add" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
            </form>
        </div>

      <a href="#" id="add" title="Add Folder" class="icon-plus icon-black"></a>
      <a href="#" title="Delete Folder" class="icon-minus icon-black"></a>
      <a href="#" title="Edit Folder" class="icon-folder-open icon-black" ></a>
  </div>

使用Javascript:

$("#message_submit").on("click", function(e){
    e.preventDefault();
      var data = $("p").find("#folder_name").val()
      console.log(data); // Testing data

     $.ajax({
        url: '<?php echo base_url().'account/members_home/add_folder';?>', 
        type: 'POST',
        data: { val: data },
        success: function(output_string){
            $(".success").text("Your folder was added!!").show().css({"color" : "green", "margin-top" : "10px"});
            $(".success").fadeOut(10000);
        }
      });

    deselect();
    $.ajax({
      url: '<?php echo base_url().'account/members_home/getFolderID';?>', 
      type: 'POST',
      data: { val1: data },
      dataType: 'json',  
      success: function(output_string){
         console.log(output_string['folder_id'][0]); // The request works
         showFolders(output_string['folder_id'][0]);

          // THIS IS THE PART WHERE I AM TRYING TO REPOPULATE THE SELECT MENU
         var newSelect = $('<option value="' + output_string['folder_id'][0] + '" >' + data + '</option>');
         $('#basic-combo').append(newSelect);
         $("#basic-combo option[value='" + output_string['folder_id'][0] + "']").attr('selected', 'selected'); 
       }
    });   

});

2 个答案:

答案 0 :(得分:0)

试试这个:

var mySelect = $('#basic-combo');
mySelect.append(
    $('<option></option>').val(output_string['folder_id'][0]).html('folder name goes here').attr("selected", "selected")
);

答案 1 :(得分:0)

我最终将此用于你想要知道的人:

$('#folder_select').append(
     $('<option></option>', {value: val2, text: data})).val(val2);