I have the following html. Please have a look at it and I will explain the problem as and when we go along.
<table>
<tbody>
<tr id="<?php echo $record['id']?>" style="...">
<td><?php echo $record['id']; ?></td>
<td><?php echo $record['url']; ?></td>
<td><input type="button" name="edit" value="Edit" onclick="edit(<?php echo ($record['id'])?>)"></td>
</tr>
</tbody>
</table>
What I am trying to achieve here is that when I click the "Edit" button, it clears that field and creates new empty fields in its place where those details can be entered again and in place of the edit button, the update button appears.
This is what the edit function looks like:
<script>
function edit(id){
var element = document.getElementById(id);
$(element).empty();
$(element).append("<td><input name='id' value="+id+" disabled></td>" +
"<td><input type='text' name='url' ></td>" +
"<td><input type='text' name='title'></td>" +
"<td><input type='button' value='Update' onclick='testFunction()'></td>");
}
The update button fires a function called testFunction. Now in this testFunction, I want to send the new values into the new form that I have created with jQuery so that I can send those values to the MySQL so that the new value of title is updated for a given id.
Please look over the code and tell me how should I go about solving this?
var testFunction = function(newID){
console.log("This is the NEW id of the object that we are changing----->");
console.log(newID);
console.log("--------------------------END------------------");
$.post( "update", { id: newID})
.done(function( ) {
document.getElementById(id).style.display = "none";
});
};
</script>
//test record
var record = {
id: 12345,
title: 'Some title',
url: 'https://stackoverflow.com/posts/45861223/edit'
};
function action(id) {
var $element = $('#' + id),
$title = $('[name=title]', $element),
$url = $('[name=url]', $element),
$btn = $('[type=button]', $element),
isUpdate = ($btn.attr('value') != 'Edit');
$title.prop('readOnly', isUpdate);
$url.prop('readOnly', isUpdate);
$btn.attr('value', isUpdate ? 'Edit' : 'Update');
if (isUpdate) {
// show some loading mask
$.post("update", {
title: $title.val(),
url: $url.val(),
id: id
})
.done(function() {
// here you have the new id from the server
// hide the loading mask
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr id="12345">
<td><input type='text' name='title' value="Some title" readOnly></td>
<td><input type='text' name='url' value="https://stackoverflow.com/posts/45861223/edit" readOnly></td>
<td><input type="button" name="edit" value="Edit" onclick="action(12345)"></td>
</tr>
</tbody>
</table>