我在html表格单元格中得到了一些可编辑的文本框!每个文本框都有一个峰会按钮。我想把textbox的值和id发送到javascript函数,这样它就可以让ajax向php脚本发出请求并编辑mysql行!
我的问题是,我不知道如何将textbox值及其相应的id传递给javascript,并在ajax响应时更改textbox按钮。我的按钮也需要唯一的id吗?有谁能告诉我这是怎么做到的吗。感谢
$table3.="<tr>";
$table3.="<td>" . $row['ID'] ."(".$totalRows. ")</td>";
$table3.="<td bgcolor='"#FF0000'"><input type='"text'" id ='"". $row['ID'] ."'" name='"". $row['ID'] ."'" value='"edit'"><button onclick='setNewValue('"".$row['ID']."'")'>Edit this Row</button></td>";
$table3.="<td>" . $row['imgPURL'] . "</td>";
$table3.="<td>" . $row['imgUrl'] . "</td>";
$table3.="<td>".$line."</td>"; echo "</tr>";
javascript:
<script>
function setNewValue(a,b) {
var button = $(event.target); // get button here
var text = $("#"+a);
var textboxvalue = text.val();
//alert("inputId:"+a+"'nuInputValue:"+b);
var url = "./edit.php";
$.post(url, {
"method": "post",
"rowId": a,
"rowValue": textboxvalue,
}, function(data)
{
var ajaxResponse = data;
//alert("success"+ajaxResponse);
if(ajaxResponse.indexOf("SuccessEdit")>=0)
{
//remote the edit button
button.hide();
}
else
{
//change caption of edit button to try again
button.text("some text");
}
})
}
</javascript>
通过类似setNewValue(23)的函数传递输入框的id
函数集NewValue(id){
$("#"+id);
}
就是这样,你可以获得输入框和的所有值
如果使用id或者更确切地说是一个类来命名提交按钮,则此操作有效;
此行:
$table3.= "<td bgcolor='"#FF0000'"><input type='"text'" id ='"". $row['ID'] ."'" name='"". $row['ID'] ."'" value='"edit'"><button onclick=''setNewValue()''>Edit this Row</button></td>";
至:
$table3.= "<td bgcolor='"#FF0000'"><input type='"text'" id ='"". $row['ID'] ."'" name='"". $row['ID'] ."'" value='"edit'"><button onclick=''setNewValue(" . $row['ID'] . ")''>Edit this Row</button></td>";
然后在你的js:
function setNewValue(id){
var text = $("#"+id);
var value = text.val();
}
更新、隐藏按钮或更改标题
function setNewValue(id){
var button = $(event.target); // get button here
// change caption
button.text("some text");
// hide
button.hide();
}
$table3.="<tr>";
$table3.="<td>" . $row['ID'] ."(".$totalRows. ")</td>";
$table3.="<td bgcolor='"#FF0000'"><input type='"text'" id ='"". $row['ID'] ."'" name='"". $row['ID'] ."'" value='"edit'"><button onclick=''setNewValue(this)''>Edit this Row</button></td>";
$table3.="<td>" . $row['imgPURL'] . "</td>";
$table3.="<td>" . $row['imgUrl'] . "</td>";
$table3.="<td>".$line."</td>"; echo "</tr>";
"this"将引用被单击的按钮元素。
function setNewValue(btn) {
var cell = btn.parentNode.querySelector("input[type='text']");
var input = cell.querySelector("input[type='text']");
var inputId = input.id;
您可以像传递普通js参数一样传递
<input type=text id = <?php echo $row['id']; ?> onclick= setNewValue(<?php echo $row['id']; ?>);
function setNewValue(id){
var obj = $("#"+id);
console.log(obj);
}
请记住,如果他正在使用元素,则默认类型为submit,并且他的整个表单可能会提交。在JS事件上添加type="button"或使用event.prventDefault()。