2013-03-02 124 views
0

我很新,使用jQuery和JavaScript,但在這裏。我正在嘗試爲我的網站創建切換功能。有一個輸入來選擇顯示爲默認的事件名稱作爲數據庫中所有事件的下拉列表 - 但我希望有一個選項可以將其更改爲手動輸入並鍵入事件的名稱作爲你想要的。jQuery切換 - 從選擇輸入更改爲文本輸入

我可以得到這個工作正常!但是,我無法獲得鏈接將輸入BACK更改爲選擇框來工作。

見下面我的代碼:

/// jQuery代碼///

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> 
<script type="text/javascript"> 
    function toggleEventInput() { 
     $("#EventNameDropDown") 
.replaceWith('<input type="text" size="35" name="boxEvent" class="FieldInput" />'); 
     $("#EventNameChange") 
.replaceWith('<a href="javascript:toggleEventInputBack();"> (Drop Down Input)</a>'); 
    } 

    function toggleEventInputBack() { 
     $("#EventNameDropDown") 
.replaceWith('TEST'); 
     $("#EventNameChange") 
.replaceWith('<a href="javascript:toggleEventInput();"> (Manual Input)</a>'); 
    } 
</script> 

/// HTML代碼///

<table> 
     <tr> 
     <td class="label">Event:</td> 
      <td> 
       <span id="EventNameDropDown"> 
       <select name="boxEvent" class="FieldInput" style="width:254px;" /> 
       <?= $EventNameDropDownList ?> 
       </select> 
       </span> 
       <span id="EventNameChange"> 
       <a href="javascript:toggleEventInput();"> (Manual Input)</a> 
       </span> 
      </td> 
     </tr> 
     <tr> 
      <td class="label">Company:</td> 
      <td><input type="text" size="35" name="boxEvent" class="FieldInput" /></td> 
     </tr> 
</table> 

至於說,當你點擊原始鏈接到'(手動輸入)'它工作正常,並將其更改爲文本框。但是當你點擊'(Drop Down Input)'鏈接時,它什麼都不做。

任何幫助,將不勝感激。

+0

兩件事情你應該糾正。 「公司」輸入元素具有與「事件」輸入相同的名稱。他們都是「boxEvent」。您的選擇標籤末尾還有一個「/」。 – 2013-03-02 18:37:58

+0

對不起,我在這裏發佈這篇文章後意識到「boxEvent」的雙倍。我已在網站上更正了這一點。 – 2013-03-02 18:40:09

回答

0

您需要使用.html()而不是.replaceWith()。前者替換元素的內容。後者取代了元素本身。通過使用.replaceWith(),您將替換包含<select><span>

克里希納建議,而不是僅僅替換<select>的html,您首先將它存儲在一個變量中,以便稍後可以放回。

你可以把它作爲存儲數據的元素,像這樣:

function toggleEventInput() { 
    // Store the html for the <select>. 
    $('#EventNameDropDown').data('selectHtml', $('#EventNameDropDown').html()); 

    $("#EventNameDropDown").html('<input type="text" size="35" name="boxEvent" class="FieldInput" />'); 
    $("#EventNameChange").html('<a href="javascript:toggleEventInputBack();"> (Drop Down Input)</a>'); 
} 

function toggleEventInputBack() { 
    $("#EventNameDropDown").html($('#EventNameDropDown').data('selectHtml')); 
    $("#EventNameChange").html('<a href="javascript:toggleEventInput();"> (Manual Input)</a>'); 

    // Clear the html for the <select>. We will get it again later if we need it. 
    $('#EventNameDropDown').data('selectHtml', ''); 
} 
+0

謝謝你約翰S.那很完美! 非常感謝您的幫助! – 2013-03-02 19:27:11

+0

不客氣。請點擊接受答案。你也可以上調克里希納的答案,因爲它有幫助。 – 2013-03-02 19:34:33

+0

接受。不會讓我投票贊成克里希納的答案,因爲它說我需要15代表?這是我第一次在這個網站上。 無論如何,如果他正在讀這個 - 也謝謝你!非常感激! – 2013-03-03 13:56:27

0

最好在div/span內添加下拉列表,同時單擊切換按鈕,將div/span內的數據存儲到變量中,並用輸入框替換內容。在下一個切換時,用變量中的數據替換div/span。狀態變量0/1將幫助切換數據。

+0

林不知道我明白如何做到這一點。你能幫助一下嗎? – 2013-03-02 18:35:04

+0

例如使用隱藏的元素,如:'

' – Jellema 2015-08-31 15:18:36