Javascript Displaying Data From Local Storage Array Problem
Solution 1:
do something like that...
const
myForm = document.forms['my-form'] // unique reference for ALL form's elements
, myTableTBody = document.querySelector('#myTable tbody')
, dataNL = JSON.parse(localStorage.getItem('dataNL') || '[]')
;
// init table
dataNL.forEach(row=>
{
let newRow = myTableTBody.insertRow()
newRow.insertCell().textContent = row.no
newRow.insertCell().textContent = row.inputNL
newRow.insertCell().textContent = row.inputJK
newRow.insertCell().textContent = row.inputNH
newRow.insertCell().textContent = row.inputA
newRow.insertCell().textContent = ''
})
myForm.onsubmit = e =>
{
e.preventDefault()
// add entries into local storage :
dataNL.push(Object.fromEntries(newFormData(myForm).entries()))
localStorage.setItem('dataNL', JSON.stringify( dataNL ))
// insert new row let newRow = myTableTBody.insertRow()
newRow.insertCell().textContent = myForm.no.value
newRow.insertCell().textContent = myForm.inputNL.value
newRow.insertCell().textContent = myForm.inputJK.value
newRow.insertCell().textContent = myForm.inputNH.value
newRow.insertCell().textContent = myForm.inputA.value
newRow.insertCell().textContent = ''// Action
}
Solution 2:
First of all:
- change
<formclass="task-form"name="my-form"onsubmit="event.preventDefault();onFormSubmit();"autocomplete="off">
to
<formclass="task-form"name="my-form"autocomplete="off">
Js code for that is :
const
myForm = document.forms['my-form'] // form name pada tag html form//....
myForm.onsubmit = e =>
{
e.preventDefault()
//...
- add my CSS from snippet below (masked)
How do you delete the local storage data?
There were some inconsistencies in the management of no
.
I made a few other fixes.
Deleting a <table><TR>
works...
And please don't use getElementById
for form elements!
see how I coded your validate()
function
see my previous posts on this point : Jun 30 at 13:06 and Jun 14 '19 at 14:17
I'm like all coders, once I get started on a project I can't just leave it halfway. I hope this will help you better finalize yours.
I got a bit of a headache on the display of the text address transposed in the table, with its overflow problems; hence the idea of the regex to at least remove unnecessary white lines ... so, see also Single regex to remove empty lines and double spaces from multiline input
const
myForm = document.forms['my-form'] // form name pada tag html form
, myTable = document.querySelector('#myTable')
, myTbody = document.querySelector('#myTable tbody')
, dataArr = JSON.parse(localStorage.getItem('dataArr') || '[]')
, rowsInfo =
{ last_no : 0
, noSelect : true
, index : 0
, tRow : null
}
, addTableRow = row =>
{
rowsInfo.last_no = Math.max( rowsInfo.last_no, row.no )
let newRow = myTbody.insertRow()
newRow.insertCell().textContent = row.no
newRow.insertCell().textContent = row.inputNL
newRow.insertCell().textContent = row.inputJK
newRow.insertCell().textContent = row.inputNH
newRow.insertCell().innerHTML = `<div>${row.inputA}</div>`
newRow.insertCell().innerHTML = `<i class="fas fa-times"></i>`
};
dataArr.forEach(addTableRow) // Tabel init
;
myForm.onsubmit = e =>
{
e.preventDefault()
if (validate())
{
if (rowsInfo.noSelect)
{
let newRow = Object.fromEntries(newFormData(myForm).entries())
newRow.no = ++rowsInfo.last_no
dataArr.push(newRow)
addTableRow (newRow) // Memasukkan Data pada Baris Baru
}
else
{
let
index = rowsInfo.index
, eTR = rowsInfo.tRow
;
eTR.cells[1].textContent = dataArr[index].inputNL = myForm.inputNL.value
eTR.cells[2].textContent = dataArr[index].inputJK = myForm.inputJK.value
eTR.cells[3].textContent = dataArr[index].inputNH = myForm.inputNH.value
dataArr[index].inputA = myForm.inputA.value
eTR.cells[4].innerHTML = `<div>${myForm.inputA.value}</div>`
eTR.classList.remove('selected')
}
localStorage.setItem('dataArr', JSON.stringify( dataArr )) // Menambahkan entri ke LocalStorage resetForm()
}
}
functionresetForm() // Function untuk Mereset Data yang sudah diSumbit di dalam Input
{
myForm.reset()
rowsInfo.noSelect = true
}
functionvalidate() // Function untuk Memvalidasi Data
{
myForm.inputNL.value = myForm.inputNL.value.trim()
myForm.inputJK.value = myForm.inputJK.value.trim()
myForm.inputNH.value = myForm.inputNH.value.trim()
myForm.inputA.value = myForm.inputA.value.replace(/^\s*$[\r\n]*|^[^\S\r\n]+|[^\S\r\n]+$|([^\S\r\n]){2,}/gm, '$1')
myForm.inputA.value = myForm.inputA.value.replace(/\n*$/, '') // remove final line breaklet isValid =
( myForm.inputNL.value !== ''
&& myForm.inputJK.value !== ''
&& myForm.inputNH.value !== ''
&& myForm.inputA.value !== ''
)
if (!isValid) alert('Isi Semua Formnya dengan Benar!')
;
return isValid
}
myTbody.onclick = ({target}) =>
{
let
eTR = target.closest('tr')
, rowNo = parseInt( eTR.cells[0].textContent )
, index = dataArr.findIndex(x=>x.no===rowNo)
, isDel = target.matches('i.fa-times, td:nth-of-type(6)')
;
if (!eTR.classList.toggle('selected') && !isDel )
{
resetForm()
}
else
{
myTbody.querySelectorAll('tr').forEach(tr=>tr.classList.toggle('selected', eTR===tr))
rowsInfo.noSelect = false
rowsInfo.index = index
rowsInfo.tRow = eTR
myForm.no.value = dataArr[index].no
myForm.inputNL.value = dataArr[index].inputNL
myForm.inputJK.value = dataArr[index].inputJK
myForm.inputNH.value = dataArr[index].inputNH
myForm.inputA.value = dataArr[index].inputAif (isDel && confirm('Apa kamu yakin ingin Menghapus Data ini?'))
{
dataArr.splice(index, 1)
myTable.deleteRow(eTR.rowIndex)
localStorage.setItem('dataArr', JSON.stringify(dataArr))
resetForm()
rowsInfo.last_no = dataArr.reduce((mx,{no})=>Math.max(mx,no),0)
}
} }
#myTable {
table-layout : fixed; /* one of the Boostrap always missing... */
}
#myTabletbodytr.selected {
background-color : darkblue;
color : whitesmoke;
}
#myTabletbodytr:hover {
background-color : lightblue;
cursor : pointer;
}
#myTabletbodytr.selected:hover {
background-color : #1c1ce0;
}
#myTabletbodytd:nth-of-type(5) div {
max-height : 1.2em; /* no multilines displaying */white-space : pre;
overflow : hidden;
}
#myTableth:nth-of-type(1),
#myTabletd:nth-of-type(1),
#myTableth:nth-of-type(6),
#myTabletd:nth-of-type(6) {
width : 4em;
text-align : center;
}
#myTabletbodytd:nth-of-type(6):hover {
color : red;
}
<linkhref="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css"integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We"crossorigin="anonymous"><linkhref="https://use.fontawesome.com/releases/v5.13.0/css/all.css" ><!-- Registration Form --><divclass="container w-50 mt-3 shadow p-3 mb-5 bg-white rounded"><divclass="p-3"><h1class="mb-4">Registration Form</h1><formclass="task-form"name="my-form"autocomplete="off"><inputtype="hidden"name="no"id="no"value=""><labelfor="inputNL"class="form-label">Nama Lengkap</label><inputtype="text"id="inputNL"name="inputNL"class="form-control mb-2"placeholder="Nama Lengkap"><labelfor="inputJK"class="form-label">Jenis Kelamin</label><selectclass="form-select mb-2"id="inputJK"name="inputJK"><optionvalue="Pria">Pria</option><optionvalue="Wanita">Wanita</option></select><labelfor="inputNH"class="form-label">No HP</label><inputtype="rowsInfo.last_no"id="inputNH"name="inputNH"class="form-control mb-2"placeholder="No HP"><labelfor="inputA"class="form-label">Alamat</label><textareaid="inputA"name="inputA"class="form-control mb-2"style="min-width: 100%"placeholder="Alamat"></textarea><inputtype="submit"value="Submit"class="btn btn-primary btn-md my-3"></form></div></div><!-- Table --><divclass="container mt-3 shadow p-3 mb-5 bg-white rounded"><divclass="p-3"><tableclass="table"id="myTable"><thead><thscope="col">#</th><thscope="col">Nama Lengkap</th><thscope="col">Jenis Kelamin</th><thscope="col">No HP</th><thscope="col">Alamat</th><thscope="col">Aksi</th></thead><tbody></tbody></table></div></div>
PS: I use exclusively Whitesmiths style
Post a Comment for "Javascript Displaying Data From Local Storage Array Problem"