首页 > 解决方案 > ajax成功后在文本框中保留值

问题描述

我有一个选择框,其中包含选项 X 和 O。我在其上放置了一个函数 Onchange 以填充文本框中的值。

<input type="text" id="remarks1"/>

这是我用于选择框在文本框中填充值的脚本:

$(document).on('click', '#1', function() { ////---make td transform to dropdown list box when click---///
      if($(this).find('select').length == 0) {
          $(this).empty();  //clears out current text in the table
          $(this).append('<select onchange="myFunction()" id="Remarks" name="Remarks"><option value=""></option><option <?php if ($Remarks=='X') echo 'selected';?> value="X" style="font-size:20px;font-weight:bold;">X<option style="font-size:20px;color:green;font-weight:bold;" <?php if ($Remarks=='O') echo 'selected';?> value="O">O</select>');
      }
});



function myFunction(){
        var dropdown1= document.getElementById("Remarks"); ////===== select box
        var selection1 = dropdown1.value;
        //console.log(selection1);
        var emailTextBox1 = document.getElementById("remarks1"); //==== textbox
        emailTextBox1.value = selection1;
     }

那么这是我点击按钮保存时的ajax:

 $(document).on('click','#btnSave',function(){
            var employeeName = document.getElementById('employeeName').value;
            var r1 = document.getElementById('remarks1').value;
            var r2 = document.getElementById('remarks2').value;

            $.ajax({
                    type: 'post',
                    url: 'update_data.php',
                    data: {
                        'DAY1' :r1,
                        'DAY1_A' :r2,
                        'employeeName' :employeeName

                    },
                    success: function(data){
                        $("#content").html(data)
                        $(".loader").fadeOut("very slow");              
                        $("#content").hide().fadeIn(500)

                        alert("Changes Succesfully Saved!");


                    },
                    error:function(data){
                        alert('Failed');
                    }
                })  

    });

ajax成功后如何保留文本框的值?

标签: javascriptlocal-storage

解决方案


您可以使用localStorage来存储该值,以便以后使用:

function myFunction(){
    var dropdown1= document.getElementById("Remarks"); ////===== select box
    var selection1 = dropdown1.value;
    localStorage.setItem('remarks', selection1); // set the value in localStorage
    var emailTextBox1 = document.getElementById("remarks1"); //==== textbox
    emailTextBox1.value = selection1;
 }

然后在 AJAX成功

success: function(data){
           $("#content").html(data)
           $(".loader").fadeOut("very slow");              
           $("#content").hide().fadeIn(500)
           var remarks = localStorage.getItem('remarks'); // get from localStorage
           document.getElementById("remarks1").value = remarks; // set the value in the text box;
           alert("Changes Succesfully Saved!");
        }

推荐阅读