每次添加新数据时,select选项中的所有值都将保存到所有数据库。 我想只保存所选的选项。 Php,Javascript [关闭]
问题描述:
i have this javascript CODE in index.php:
$(document).on('blur', '.first_name', function(){
var id = $(this).data("id1");
var first_name = $(this).text();
edit_data(id, first_name, "first_name");
});
$(document).on('blur', '.last_name', function(){
var id = $(this).data("id2");
var last_name = $(this).text();
edit_data(id,last_name, "last_name");
});
$(document).on('blur', '.gender', function(){
var id = $(this).data("id3");
var gender= $(this).text();
edit_data(id,gender, "gender");
});
AND in select.php:
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td class="first_name" data-id1="'.$row["id"].'" contenteditable>'.$row["first_name"].'</td>
<td class="last_name" data-id2="'.$row["id"].'" contenteditable>'.$row["last_name"].'</td>
<td><select class="type" data-id3="'.$row["id"].'">
<option>'.$row["gender"].'</option>
<option>male</option>
<option>female</option>
</select></td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
ALSO in edit.php here:
<?php
$connect = mysqli_connect("localhost", "root", "", "test");
$id = $_POST["id"];
$text = $_POST["text"];
$column_name = $_POST["column_name"];
$sql = "UPDATE tbl_sample SET ".$column_name."='".$text."' WHERE id='".$id."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Updated';
}
?>
My question is, everytime i add new data, all the text in gender option will save to database. i want to save only the selected option. Please help me.
答
all the text in gender option will save to database
Well yes, this is what happens when you use $(this).text();
Gender is a select input, not a text field (where .text()
works fine). Therefore you should use
var gender= $(this).val();
Edit: it's .val()
, not .value()
答
$(document).on('blur', '.type', function(){
var id = $(this).data("id3");
var gender= $(this).val();
edit_data(id,gender, "gender");
});
Use this code for update user gender type in database.
First you get wrong element for gender please use .type not .gender and 2nd you grab all the text in dropdown it's not good code practice. use this .val()
not .text()
on input fields.
PHP code
$m = $row["gender"] == "male" ? "selected" : "";
$f = $row["gender"] == "female" ? "selected" : "";
$output .= '
<tr>
<td class="first_name" data-id1="' . $row["id"] . '" contenteditable>' . $row["first_name"] . '</td>
<td class="last_name" data-id2="' . $row["id"] . '" contenteditable>' . $row["last_name"] . '</td>
<td><select class="type" data-id3="' . $row["id"] . '">
<option>select</option>
<option value="male" ' . $m .'>male</option>
<option value="female" '. $f .'>female</option>
</select></td>
<td><button type="button" name="delete_btn" data-id3="' . $row["id"] . '" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';