Question:
I am programming a script that contains a button; which develops a function that searches by identification number for a record (object).
This is the function:
function buscarobjeto(){
var transaction = db.transaction(["gente"],"readonly");
var objectStore = transaction.objectStore("gente");
var ob = objectStore.get(numero);
bd.onsuccess = function(e) { }
This is the code I have so far.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Base de Datos con JavaScript</title>
<script type="text/javascript">
var bd;
function iniciar(){
MostrarDatos=document.getElementById("MostrarDatos");
boton=document.getElementById("grabar");
boton.addEventListener("click",agregarobjeto, false);
boton=document.getElementById("buscar");
boton.addEventListener("click",buscarobjeto, false);
var solicitud=indexedDB.open("sistemas");
solicitud.onsuccess=function(e){
bd=e.target.result;
}
solicitud.onupgradeneeded=function(e){
bd=e.target.result;
bd.createObjectStore("gente", {keyPath: "nombre"});
}
}
function agregarobjeto(){
var nombre=document.getElementById("nombre").value;
var apellido=document.getElementById("apellido").value;
var identificacion=document.getElementById("identificacion").value;
var numero=document.getElementById("numero").value;
var facultad=document.getElementById("facultad").value;
var programa=document.getElementById("programa").value;
var semestre=document.getElementById("semestre").value;
var asignatura=document.getElementById("asignatura").value;
var transaccion=bd.transaction(["gente"], "readwrite");
var almacen=transaccion.objectStore("gente");
var agregar=almacen.add({nombre: nombre, apellido: apellido, identificacion: identificacion, numero: numero, facultad: facultad,
programa: programa, semestre: semestre, asignatura: asignatura});
agregar.addEventListener("success", mostrar, false);
document.getElementById("nombre").value=""
document.getElementById("apellido").value=""
document.getElementById("identificacion").value=""
document.getElementById("numero").value=""
document.getElementById("facultad").value=""
document.getElementById("programa").value=""
document.getElementById("semestre").value=""
document.getElementById("asignatura").value=""
}
function mostrar(){
MostrarDatos.innerHTML="";
var transaccion=bd.transaction(["gente"],"readonly");
var almacen=transaccion.objectStore("gente");
var cursor=almacen.openCursor();
cursor.addEventListener("success", mostrarDatos, false);
}
function buscarobjeto(){
}
window.addEventListener("load", iniciar, false);
var elements = [];
function mostrarDatos(e){
var cursor=e.target.result;
if(cursor){
MostrarDatos.innerHTML+="<div><table border=1></caption><thead>"
+ "<tr> <td width=85>" + cursor.value.nombre
+ "</td><td width=85>" + cursor.value.apellido
+ "</td><td width=85>" + cursor.value.identificacion
+ "</td><td width=85>" + cursor.value.numero
+ "</td><td width=85>" + cursor.value.facultad
+ "</td><td width=85>" + cursor.value.programa
+ "</td><td width=85>" + cursor.value.semestre
+ "</td><td width=85>" + cursor.value.asignatura
+ "</td></tr></thead></table></div>";
cursor.continue();
}
}
</script>
</head>
<body>
<form name="formulario">
<div id="contenedor">
<section id="cajaformulario">
<table border=1>
<caption><B>Registro de Estudiantes</B></caption>
<thead>
<tr>
<th><input type="text" id="nombre" placeholder="Introducir nombre" /></th>
<th><input type="text" id="apellido" placeholder="Introducir apellido" /></th>
<th><input type="text" id="identificacion" placeholder="Introducir tipo identificacion" /> </th>
<th><input type="text" id="numero" placeholder="Introducir # de identificación" /></th>
</tr>
<tr>
<th><input type="text" id="facultad" placeholder="Introducir facultad" /></th>
<th><input type="text" id="programa" placeholder="Introducir programa" /></th>
<th><input type="text" id="semestre" placeholder="Introducir semestre" /></th>
<th><input type="text" id="asignatura" placeholder="Introducir asignatura" /></th>
</tr>
<tr>
<th colspan=7><button type="button" name="grabar" id="grabar" value="Grabar">Guardar</button></th>
</tr>
<tr>
<th colspan=7><button type="button" name="buscar" id="buscar" value="Buscar">Buscar</button></th>
</tr>
</thead>
</table>
</section>
</div>
<div id="elements">
<section id="MostrarDatos">
<table border=1>
<caption><B>Estudiante(s) Registrado(s)</B></caption>
<thead>
<tr>
<td width=85><B><Center>Nombre</B></td>
<td width=85><B><Center>Apellido</B></td>
<td width=135><B><Center>T de Identificación</B></td>
<td width=135><B><Center>N de dentificacion</B></td>
<td width=85><B><Center>Facultad</B></td>
<td width=85><B><Center>Programa</B></td>
<td width=85><B><Center>Semestre</B></td>
<td width=85><B><Center>Asignatura</B></td>
</tr>
</thead>
<tbody id="cursor">
<tr>
<td colspan="9">No hay elementos a mostrar</td>
</tr>
</tbody>
</table>
</section>
</div>
</form>
</body>
</html>
Answer:
What is wrong
The search function shown in the question has some problems. Let's see them one by one:
function buscarobjeto(){
var transaction = db.transaction(["gente"],"readonly");
var objectStore = transaction.objectStore("gente");
var ob = objectStore.get(numero);
bd.onsuccess = function(e) { }
}
- The database is in
bd
but the transaction is done indb
. -
numero
is not the name of a variable, but the name of the column / index you want to search and you should enclose it (although as I explain later, it could be correct but there are more things that would need changes here). - The
onsuccess
event occurs inob
but is being listened to inbd
. - The
onsuccess
event is empty, so even if something is found, no operation is being performed on the result.
But there is still more. Even if the above errors are fixed, there would still be problems with how the database is created:
bd.createObjectStore("gente", {keyPath: "nombre"});
It is specified that the key is going to be "name", but no other field is indicated as index ( index ), so it will not be possible to search for anything other than "name" and not for any other field.
How to solve it
Start by adding an index on the "number" column to be able to search for it:
var ob = bd.createObjectStore("gente", {keyPath: ["nombre"]});
ob.createIndex("numero", "numero", { unique: false });
Note: Using the name as a password is not a good idea. As the table is defined, the key is "name" so it will not be allowed to have two records / people with the same name. I've left it this way to modify the code as little as possible, but I really think you should reconsider the keys.
Now that you have the column "number" as an index, let's make some changes to the buscarobjeto
function:
function buscarobjeto(){
MostrarDatos.innerHTML="";
var numero = document.getElementById("numero").value;
var transaction = bd.transaction(["gente"],"readonly");
var objectStore = transaction.objectStore("gente");
var index = objectStore.index("numero");
var ob = index.openCursor(numero);
ob.addEventListener("success", mostrarDatos, false);
}
And in this way, the records whose number is identical to the one written in the "number" field of the form will be searched (there may be more than one because the field is not unique when it is created).
The changes that have been made to the function:
- We delete the
div
with the results where the data will be displayed. - We read the "number" field and store it in a variable.
- We indicate that it will be searched by the index "number" (
var index = objectStore.index("numero");
) - We open a cursor to traverse the results (again, this may not be the optimal way to do it, but it is to be able to reuse the existing code).
- We associate the
onsuccess
event withmostrarDatos
so that the results are displayed in the same way as when a record is inserted.