尝试保存时将文本区域设置为 display:none 会丢失值

Setting textarea to display:none loses the value when trying to save

我有一个文本区域,用户可以在其中输入注释。但是这个文本区域只有在复选框被勾选时才会显示,否则它是隐藏的。 但是当单击保存按钮并将值保存到数据库时,textarea 返回一个空白值。

文本区域代码:

<textarea class="mceEditorWide" id="txtAddDetailNote" rows="30" cols="50" style="width:100%;display:none" runat="server"></textarea>

hides/shows 文本框的复选框:

 $('#<%= chkNotes.ClientID %>').change(function () {
        if($(this).is(":checked")) {
             $('#<%= txtAddDetailNote.ClientID %>').show(); 
            } 
        else { 
               $('#<%= txtAddDetailNote.ClientID %>').hide(); 

            }
    });

当我从文本区域中删除 display:none 时,它会保存该值。但是在代码中使用 display:none,它只有 returns 一个空白值,即使当我单击保存按钮时文本区域正在显示。

您必须在文本框中使用属性禁用。那么只有它不会 return anything.if 你使用 display:none 它不会在浏览器中的文本框但是它发送空值到 post

上的控制器

文本框代码:

<textarea class="mceEditorWide" id="txtAddDetailNote" rows="30" cols="50" style="width:100%;display:none" runat="server"></textarea>

hides/shows 文本框的复选框:

 $('#<%= chkNotes.ClientID %>').change(function () {
        if($(this).is(":checked")) {
             $('#<%= txtAddDetailNote.ClientID %>').removeAttr('disabled','disabled').show();
            } 
        else { 
               $('#<%= txtAddDetailNote.ClientID %>').attr('disabled','disabled').hide();

            }
    });

希望这对您有所帮助

您可以切换元素的 visibility css 样式:

$("#someSelector").css("visibility", "collapse");
$("#someSelector").css("visibility", "visible");

...如有必要,将其高度设置为亚像素值,例如 0.001px

我不太明白你要做什么,你能提供更多代码吗?一个fiddle?

试试这个:

$('.checkbox').change(function() {
  var ShowHide = $(this).is(":checked") ? $('.mceEditorWide').show() : $('.mceEditorWide').hide();
});


$(document).on('submit', $('form'), function(e) {
  e.preventDefault();
  alert($('.mceEditorWide').val());
})

showing/hidingtextarea 有一个更简单的实现,当您提交表单时,您可以看到提醒的 textarea 的值。

这是一个工作示例:

https://jsfiddle.net/nebulousal/4bnjfLc8/

此外,您可以插入自己的代码来拦截表单提交,并在发送到服务器之前对要发送到服务器的实际数据执行任何您想做的事情:

$(document).on('submit', $('form'), function(e) {
  e.preventDefault();
  //Do whatever you want to do to any data in the form
  //Then send it off to the server
})

本题答案: 仍然不确定为什么将文本区域设置为 display:none 导致它丢失值,但是将显示设置为 <tr> 标签解决了这个问题。

文本区域代码:

<tr class ="trNotes" style="display:none">
            <td class="tblAddDetail" colspan="10">
                <textarea class="mceEditorWide" id="txtAddDetailNote" rows="30" cols="50" style="width:100%;" runat="server"></textarea>
            </td>
        </tr> 

编码为hide/show它:

$('#<%= chkNotes.ClientID %>').change(function () {
        if($(this).is(":checked")) {
                $('.trNotes').show();
            } 
        else { 
                $('.trNotes').hide(); 
            }
    });

display:none 设置为 <tr> 并为其指定 class 名称不会影响文本区域中的值。