2011-06-26 19 views
0

使用jQuery/jQueryUI我想用下面的HTML/JS顯示填充表單。.get返回的數據形式允許.html填充表單?

url「editController/loadContents」將返回一些數據,而.html將(根據數據填充表單),但數據應具有哪些結構?

我可以在jQueryUI doco中找到的唯一示例是單元素窗體。

我的猜測是,一些JSON它看起來像這樣...

{ 
    "starttime": "10:00", 
    "endtime": "11:00", 
} 

...將填充輸入字段。但是,如何提供SELECT選項,並將選項之一指定爲「選定」?

<div id="dialog" title="Basic dialog"> 
    <!-- loaded from ajax call --> 
    <form id="exampleForm"> 
    <fieldset> 
    <label for="activity">Activity</label> 
    <br /> 
    <select name="activity" id="activity" class="ui-widget-content ui-corner-all"> 
    </select> 
    <br /> 
    <label for="subactivity">Sub-Activity</label> 
    <br /> 
    <select name="subactivity" id="subactivity" class="ui-widget-content ui-corner-all"> 
    </select> 
    <br /> 
    <label for="activity">Reason</label> 
    <br /> 
    <select name="reason" id="reason" class="ui-widget-content ui-corner-all"> 
    </select> 
    <br /> 
    <label for="starttime">Start</label> 
    <br /> 
    <input type="text" name="starttime" id="starttime" class="text ui-widget-content ui-corner-all" /> 
    <br /> 
    <label for="endtime">End</label> 
    <br /> 
    <input type="text" name="endtime" id="endtime" class="text ui-widget-content ui-corner-all" /> 
    <br /> 
    </fieldset> 
    <input type="button" onclick="Save()" /> 
    </form> 


</div> 

<script> 
    $(function() { 
     $('.myPop').click(function() { 
      $.get("editController/loadContents", function(data){ 
      $("#dialog").html(data); 
      });   
      $("#dialog").dialog('open'); 
     }); 
    }); 


function Save(){ 
$.post("/editController/Edit", $("#exampleForm").serialize(), 
    function(data){ 
    $("#dialog").dialog('close'); 
    //update grid with ajax call 
    }); 
} 

</script> 

BTW我已經適應在How to use a jQuery UI Modal Form from ASP.Net MVC list page

回答

0

的.html從非常有用的答案這段代碼(我相信)填充基於數據的 形式,但什麼 結構應的數據有?。

.html()只是將jQuery選擇器中匹配元素的HTML內容設置爲您提供的內容。基於JSON對象的現有輸入沒有自動設置值。

這使你有兩個選擇:

  1. 讓您的服務器端代碼返回你盲目使用.html()用填充HTML表單,或
  2. 編寫JavaScript你找回原始數據進行關聯您的頁面上存在input的服務器。

但如何爲 選擇選項提供和指定爲「選擇」的的 選項之一?

動態插入選項到現有select元素,你可以簡單地生成一個新的option元素和.append()它:

$("<option>") 
    .text("Swimming") 
    .attr("selected", true) // Set the option's "selected" attribute 
    .attr("value", 1) 
    .appendTo("#activity"); 

很明顯,你將不得不代碼適應你的JSON數據從您的服務器端代碼返回,可能會循環訪問您返回的一系列活動,併爲每個活動創建一個新的option

+0

非常感謝非常有用的答案 - 我對謙卑的.html抱有更高的期望,而不是合理的! – shearichard