当我单击编辑按钮时,我想用数据库值填充表单字段。我要填充的表单负责更新日记条目的属性(包括标题和正文)。
目前,当我单击编辑按钮时,我得到一个空的编辑表单。因此,如果我想保留条目的一些现有信息(例如条目的正文),我必须在更新条目之前将条目的正文复制到编辑表单中,这是一项繁琐的任务。
我该如何实施?
更新日记条目的功能
function edit_entry(entry_id){
// open modal to edit diary entry
var modal = document.getElementById('edit_modal');
modal.style.display = "block";
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
};
document.getElementById('edit_modal').addEventListener('submit', updateDetail);
function updateDetail(e){
e.preventDefault();
let title = document.getElementById('title').value;
let body = document.getElementById('body').value;
var statusCode;
fetch('http://localhost:5000/api/v1/entries/'+parseInt(entry_id),{
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + window.localStorage.getItem('token')
},
body: JSON.stringify({
"title": title,
"body": body,
})
})
.then((result) => {
statusCode = result.status;
return result.json();
})
.then((data) =>{
window.alert(data.message);
modal.style.display = "none";
redirect: window.location.replace('./viewAllEntries.html');
});
}
}
HTML 表单
<form action="" class ="add-content" id="edit_modal">
<h2>My Diary | Edit Entry <i class="fa fa-book" aria-hidden="true"></i></h2>
<div class="form-group">
<label></label>
<textarea id = "title" class ="input-control"></textarea>
</div>
<div class="form-group">
<label></label>
<textarea id = "body" class ="input-control"> </textarea>
</div>
<div class ="form-group">
<label> </label>
<button type = "submit" class ="button button-block" />Save <i class="fa fa-floppy-o" aria-hidden="true"></i></button>
</div>
</form>
当您打开模态时,只需从您的 API 中获取条目的数据。尝试类似下面的代码。
$yourUrlToFetchTheData 应该是用于获取所需数据的 api 路由的 url。
fetch($yourUrlToFetchTheData, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + window.localStorage.getItem('token')
}
})
.then((result) => {
// TODO FILL THE TEXTAREAS WITH THE VALUES OF THE RESULT.
$("title").text(result.json.title);
$("body").text(result.json.body);
})
.then((data) => {
// TODO DO SOMETHING WITH THE ERROR.
});
将此代码放在modal.style.display = "block"; 之后 并稍微修改一下!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句