保留动态输入的文本从jquery到div

时间:2014-03-18 21:00:33

标签: javascript jquery html dynamic text

感谢这里的优秀人员,我能够整理出我之前的一个问题的工作原型 - 使用带有密码要求的文本框输入来填充元素。

现在,一切都按预期工作 - 但是,我注意到一个怪癖,我希望有人可以帮助我。为我的浏览器会话输入新值时将反映该更改,但是,访问此同一页面的任何其他人都将收到已设置的初始值。

HTML Here:

<input id="txtBox" type="textbox" value="0" style="display:none;" />
<input id="txtBox2" type="textbox" value="0" style="display:none;" /> 
<input id="passwordBox" type="password" value="" style="display: none;" />
<div id="txtBoxValue" style="height: 25px; background: #e3e3e3; width: 100px;"></div>
<div id="txtBox2Value"></div>

Javascript在这里:

$(function() {

   $('#txtBoxValue').on('click', function() {
       $(this).hide();
       $('#txtBox2Value').hide();
       $('#passwordBox').show().focus();
   });

   $('input#passwordBox').bind('keypress', function(e) {
       if(e.keyCode == 13) {
           if($(this).val() == 'password') {
               $(this).val('');
               $(this).hide();
               $('#txtBox').show().focus();
               $('#txtBox2').show();
           }
           else {
            $(this).val('');
            $(this).hide();
            $('#txtBoxValue').show();
            $('#txtBox2Value').show();
           }

       }
   });

   $('#txtBox').bind('keypress', function(e) {
       if(e.keyCode == 13) {
       var that = $(this);
       $('#txtBoxValue').text(that.val()).show();
       that.hide();
       }
   });

 $('#txtBox2').bind('keypress', function(e) {
       if(e.keyCode == 13) {
       var that = $(this);
       $('#txtBox2Value').text(that.val()).show();
       that.hide();
       }
   });

});

您可以在此处查看jsfiddle:http://jsfiddle.net/curtisrichins/Q22tG/21/

保留新信息以便为任何访问者显示该信息的最佳方式是什么,而不是默认返回原始条目值?

1 个答案:

答案 0 :(得分:0)

您将需要在服务器上存储状态 - 否则无法对所有访问者进行更改。您没有说明您正在使用的服务器端语言,但此状态可以保存在数据库或类似数据库中。

因此,就客户端代码而言,您需要使用ajax请求(或整页回发)将数据POST重新发送回服务器才能存储它。然后,在客户端代码中,您需要允许GET该数据(再次使用ajax或类似数据)。

鉴于此,您的代码将使用与以下内容模糊相似的内容进行更新:

$(function () {

    //Load data from server 
    $.get("/yourserver/handler", function(data) {
        $('#passwordBox').val(data);
    });

    //Send data to server event handler
    $('#passwordBox').blur(function() {
        //Ajax POST to server
        $.post("/yourserverurl/handler", { valueToSave: $(this).val() });
    }).fail(function() { alert("Could not save to server"); });

    //All the other event handlers, etc that you had before
    //...
    //...
});

从上面开始,我展示了在文本框上使用blur将数据发送到服务器,但这可能是任何东西 - 点击按钮或其他任何内容。