将DIV转换为输入元素并将数据保存到数据库中

时间:2013-01-15 02:38:30

标签: php javascript jquery mysql

我有一个简单的div用于显示用户帐户信息,例如名字:

<div id="firstNameChange"><?=$firstName?></div>

我有jquery代码用于将其转换为输入元素:

//execute when nameChange DIV is clicked
        $("#firstNameChange").click(function(){ 


                //check if there are any existing input elements
                if ($(this).children('input').length == 0){

                    $("#saveFirstName").css("display", "inline");

                    //variable that contains input HTML to replace
                    var inputbox = "<input type='text' class='inputbox' name='firstName' value=\""+$(this).text()+"\">";    
                    //insert the HTML intp the div
                    $(this).html(inputbox);         

                    //automatically give focus to the input box     
                    $("this .inputbox").focus();

                    //maintain the input when it changes back to a div
                    $("this .inputbox").blur(function(){
                        var value = $(this).val();
                        $("#firstNameChange").text(value);

                    });
                }               
        });

我创建了一个PHP变量来获取输入元素的内容,但它没有填充变量。由于某种原因,该变量未使用我在上面创建的JS输入元素的名称值进行设置。任何想法为什么会这样?

if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$sql = "UPDATE `user_accounts` SET `first_name`='$firstName' WHERE email='" . $_SESSION['email'] . "' AND user_id=" . $_SESSION['userID'] ;
$_dbConn->update($sql) or die(mysql_error());
Redirect_To('index.php?page=userProfile');  

}

2 个答案:

答案 0 :(得分:2)

问题是您在执行此操作时替换输入元素:

$("#firstNameChange").text(value);

一种解决方案是将HTML更改为:

<div id="firstNameChange"><?=$firstName?></div><input type="hidden" name="firstName" id="firstNameHidden"/>

然后在您的模糊功能中将隐藏的输入值设置为文本输入值,如下所示:

$("#firstNameHidden").val( value );

答案 1 :(得分:1)

你为什么要这样做? $(“this .inputbox”)。focus();

首先,“这个.inputbox”开始没用。

 $(inputbox).focus();

 //maintain the input when it changes back to a div
 $(inputbox).blur(function(){
     var value = $(this).val();
     $("#firstNameChange").text(value);
 });

另外,你是否意识到当你做$(this).html(inputbox)时;用新创建的输入元素替换DIV的所有内容?所以,你的<?=$firstName?>已经消失了。

相关问题