2013-03-02 112 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