将 DIV 转为输入元素并将数据保存到数据库中 [英] Turning a DIV into a input element and save data into a database
问题描述
我有一个简单的 div 用于显示用户帐户信息,例如名字:
I have a simple div used to display user account info such as first name:
<div id="firstNameChange"><?=$firstName?></div>
我使用 jquery 代码将其转换为输入元素:
I have jquery code used to turn it into an input element:
//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 输入元素的名称值.任何想法为什么会发生这种情况?
I created a PHP variable to grab the contents of the input element but it is not filling the variable. For some reason, the variable is not being set with the name value of the JS input element that i created above. any ideas why this is happening?
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');
}
推荐答案
问题是你在执行此操作时替换了 input 元素:
The problem is you replace your input element when you do this:
$("#firstNameChange").text(value);
一种解决方案是将您的 HTML 更改为:
One solution is to change your HTML to this:
<div id="firstNameChange"><?=$firstName?></div><input type="hidden" name="firstName" id="firstNameHidden"/>
然后在您的模糊函数中将隐藏输入值设置为文本输入值,如下所示:
Then in your blur function set the hidden input value to the text input value like this:
$("#firstNameHidden").val( value );
这篇关于将 DIV 转为输入元素并将数据保存到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!