如何使用javascript将值插入文本字段?

时间:2013-06-05 07:09:25

标签: jquery html

的Javascript

 $(document).ready(function() {


            var originaltext = $('#editable').val()

        $("#editable").keydown(function(e){
         if(e.which == 9) 
         {      
            var content = $('#editable').val(); 
            var originaltext = $('#editable').val();    
            $.ajax({
                url: 'save.php',
                type: 'POST',
                data:{
                content: content
                },
                success:function (data) {

                    if (data == '1')
                    {
                        $("#status")
                        .addClass("success")
                        .html("Data saved successfully")
                        .fadeIn('fast')
                        .delay(3000)
                        .fadeOut('slow');   

                    }
                    else
                    {
                        $("#status")
                        .addClass("error")
                        .html("An error occured, the data could not be saved")
                        .fadeIn('fast')
                        .delay(3000)
                        .fadeOut('slow');   
                    }
                }
            });   
         }

        });

        $("#editable").click(function (e) {
            $("#save").show();
            e.stopPropagation();
        });

        $(document).click(function() {

            $("#save").hide(); 
            $('#editable').value = originaltext;
        });


    });

当我点击文本框外部时,我希望文本字段恢复更改。它将恢复为数据库中的保存文本

我试过这个

$(document).click(function(){

        $("#save").hide(); 
        $('#editable').value = originaltext;
    });

但它没有用,我该怎么办?

HTML

<div id="status"></div>



        <?php
            //get data from database.
            include("db.php");
            $sql = mysql_query("select * from test where ID= '1'");
            $row = mysql_fetch_array($sql);         

        ?>      
    <input id="editable" name="editable" type="text" value="<?php echo $row['Name'];?>">


        <button id="save">Save</button>
        </div>


    </div>

1 个答案:

答案 0 :(得分:6)

您需要使用.val()

替换

 $('#editable').value = originaltext;

$('#editable').val(originaltext) ;