繁体   English   中英

jQuery切换-从选择输入更改为文本输入

[英]jQuery toggle - Changing from select input to text input

我是使用jQuery和JavaScript的新手,但现在开始。 我正在尝试为我的网站创建一个切换功能。 有一个输入可以选择事件的名称,该名称默认显示为数据库中所有事件的下拉列表-但是我希望有一个选项可以将其更改为手动输入,然后输入事件名称为你想要的

我可以使它正常工作! 但是我无法获得将输入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>

如前所述,当您单击原始链接到“(手动输入)”时,它可以正常工作并将其更改为文本框。 但是,当您单击“(下拉输入)”链接时,它没有任何作用。

任何帮助,将不胜感激。

最好在div / span内添加下拉列表,然后单击切换按钮,将div / span内的数据存储到变量中,然后将内容替换为输入框。 在下一次切换时,将div / span替换为变量中的数据。 状态变量0/1将有助于切换数据。

您需要使用.html()而不是.replaceWith() 前者替换元素的内容。 后者代替了元素本身。 通过使用.replaceWith()您也将替换包含<select><span>

克里希纳(Krishna)建议,您不要将html替换为<select> ,而是先将其存储在变量中,以便以后再放回去。

您可以将其作为数据存储在元素上,如下所示:

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', '');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM