This is my assignment : " the modif_function, view_function and add_function methods are launched when the corresponding ACTION button is clicked. The corresponding buttons are only visible if the methods have been supplied by the user by a function. "
I've been trying for many hours without success.
class Table {
id_zone = "";
class_table = "";
data = "";
header = "";
class_modif = "";
class_supp = "";
class_vue = "";
icone_modif = "";
icone_supp = "";
icone_vue = "";
constructor(
id_zone = "",
class_table = "",
data = "",
header = "",
class_modif = "",
class_supp = "",
class_vue = "",
icone_modif = "",
icone_supp = "",
icone_vue = ""
) {
this.id_zone = id_zone;
this.class_table = class_table;
this.data = data;
this.header = header;
this.class_modif = class_modif;
this.class_supp = class_supp;
this.class_vue = class_vue;
this.icone_modif = icone_modif;
this.icone_supp = icone_supp;
this.icone_vue = icone_vue;
}
generer = () => {
if (this.id_zone == "") {
throw new Error(
"Pour générer une table, il faut préciser la proprieté id_zone."
);
} else {
var table =
"<table class='" +
this.class_table +
"'>" +
"<tbody>" +
"<tr>" +
"<th>" +
donneesHeader[0] +
"</th>" +
"<th>" +
donneesHeader[1] +
"</th>" +
"<th>" +
donneesHeader[2] +
"</th>" +
"</tr>" +
"<tr></tr>";
$(this.data).each(function () {
table +=
"<tr>" +
"<td>" +
$(this)[0] +
"</td>" +
"<td>" +
$(this)[1] +
"</td>" +
"<td>" +
"<button type='button' class='" +
tableFils.class_vue +
" " +
tableFils.icone_vue +
"' " +
"value=" +
$(this)[0] +
"*" +
$(this)[1] +
"></button>" +
"<button type='button'" +
" class='" +
tableFils.class_modif +
" " +
tableFils.icone_modif +
"' value=" +
$(this)[0] +
"*" +
$(this)[1] +
"></button>" +
"<button type='button' class='" +
tableFils.class_supp +
" " +
tableFils.icone_supp +
"' value=" +
$(this)[0] +
"*" +
$(this)[1] +
">" +
"</button></td>";
});
table += "</tr></tbody></table>";
$("#zoneTable").html(table);
}
};
fonction_modif = () => {};
//What to write here
fonction_supp = () => {};
fonction_vue = () => {};
}
function supprRegion() {
alert("hello world 1");
}
function modifRegion() {
alert("hello world 2");
}
function vueRegion() {
alert("hello world 3");
}
let donnees = [
[1, "Ain"],
[2, "Aisne"],
[3, "Allier"],
[4, "Alpes-de-Haute-Provence"],
[5, "Hautes-Alpes"],
[6, "Alpes-Maritimes"],
[7, "Ardèche"],
[8, "Ardennes"],
[9, "Ariège"],
[10, "Aube"],
[11, "Aude"],
[12, "Aveyron"],
];
let donneesHeader = ["Code", "Nom du département", "Actions"];
let tableFils = new Table();
$(document).ready(function () {
tableFils.id_zone = $("#zoneTable");
tableFils.class_table = "table table-dark table-hover";
tableFils.data = donnees;
tableFils.class_modif = "mod_region";
tableFils.class_supp = "supp_region";
tableFils.class_vue = "vueRegion";
tableFils.icone_modif = "btn btn-info btn-sm fas fa-pencil-alt fa-sm";
tableFils.icone_supp = "btn btn-danger btn-sm fas fa-trash-alt fa-sm";
tableFils.icone_vue = "btn btn-success btn-sm fas fa-eye fa-sm";
tableFils.fonction_modif = modifRegion;
tableFils.fonction_supp = supprRegion;
tableFils.fonction_vue = vueRegion;
tableFils.generer();
});
HTML:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<!-- CDN CSS de BOOTSTRAP -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<!-- CDN de FONTAWSOME pour les ICONES -->
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
</head>
<body>
<div id="zoneTable"></div>
<!-------------------------------------
CDN JS pour BOOTSTRAP
--------------------------------------->
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<!-------------------------------------
Nos fichiers JS
--------------------------------------->
<script src="assets/main.js">
</script>
</body>
</html>
So, when there's a click on the modif, supp or vue icons, I get a simple alert.
But I cannot change this : " fonction_modif = modifRegion; "
Delete this:
fonction_modif = () => {};
//What to write here
fonction_supp = () => {};
fonction_vue = () => {};
And add this to properties of the class:
fonction_modif = null;
fonction_supp = null;
fonction_vue = null;
Now, you already can assign a funtion to the properties of the tableFils object, and type the call inside class code, example, as onclick inside a html element of generer function:
this.fonction_modif()
Related
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Why does mysqli num_rows always return 0?
(1 answer)
Closed 12 days ago.
I have a site that needs to list all the pets in the database so the user can edit one pet if he wants to.
bBut my code isn't working and my query to search the pets is returning nothing. here are the codes.
List.php (the one with the query) (i am getting the No user found else)
<?php
include_once "conecta.php";
$pagina = filter_input(INPUT_GET, "pagina", FILTER_SANITIZE_NUMBER_INT);
if (empty($pagina)) {
$qnt_result_pg = 40;
$inicio = ($pagina * $qnt_result_pg) - $qnt_result_pg;
$query_usuarios = "SELECT Nome_pet, especie, raca, sexo, idade, descricao FROM pet ORDER BY COD DESC LIMIT 0, $qnt_result_pg";
$result_usuarios = $conn->prepare($query_usuarios);
$result_usuarios->execute();
if ($result_usuarios->num_rows() != 0) {
$dados = "<div class='table-responsive'>
<table class='table table-striped table-bordered'>
<thead>
<tr>
<th>Nome</th>
<th>Espécie</th>
<th>Raça</th>
<th>Sexo</th>
<th>Idade</th>
<th>Descrição</th>
<th>Ações</th>
</tr>
</thead>
<tbody>";
while ($row_usuario = $result_usuarios->fetch(PDO::FETCH_ASSOC)) {
extract($row_usuario);
$dados = "<tr>
<td>$Nome_pet</td>
<td>$especie</td>
<td>$raca</td>
<td>$sexo</td>
<td>$idade</td>
<td>$descricão</td>
<td class='d-flex'>
Editar Salvar
</td>
</tr>";
}
$dados .= "</tbody>
</table>
</div>";
$query_pg = "SELECT COUNT(COD) AS num_result FROM pet";
$result_pg = $conn->prepare($query_pg);
$result_pg->execute();
$row_pg = $result_pg->fetch(PDO::FETCH_ASSOC);
$quantidade_pg = ceil($row_pg['num_result'] / $qnt_result_pg);
$max_links = 2;
$dados .= '<nav aria-label="Page navigation example"><ul class="pagination pagination-sm justify-content-center">';
$dados .= "<li class='page-item'><a href='#' class='page-link' onclick='listarUsuarios(1)'>Primeira</a></li>";
for ($pag_ant = $pagina - $max_links; $pag_ant <= $pagina - 1; $pag_ant++) {
if ($pag_ant >= 1) {
$dados .= "<li class='page-item'><a class='page-link' href='#' onclick='listarUsuarios($pag_ant)' >$pag_ant</a></li>";
}
}
$dados .= "<li class='page-item active'><a class='page-link' href='#'>$pagina</a></li>";
for ($pag_dep = $pagina + 1; $pag_dep <= $pagina + $max_links; $pag_dep++) {
if ($pag_dep <= $quantidade_pg) {
$dados .= "<li class='page-item'><a class='page-link' href='#' onclick='listarUsuarios($pag_dep)'>$pag_dep</a></li>";
}
}
$dados .= "<li class='page-item'><a class='page-link' href='#' onclick='listarUsuarios($quantidade_pg)'>Última</a></li>";
$dados .= '</ul></nav>';
$retorna = ['status' => true, 'dados' => $dados];
} else {
$retorna = ['status' => false, 'msg' => "<p style='color: #f00;'>Erro: No user found!"];
}
} else {
$retorna = ['status' => false, 'msg' => "<p style= 'color: #f00';>Erro: Pagina ruim"];
}
echo json_encode($retorna);
Custom.js
`const tbody = document.querySelector("listar-usuarios");
const listarUsuarios = async (pagina) => {
// 8887 is the port number you have launched your server
const dados = await fetch("http://127.0.0.1:8887/list.php?pagina=" + pagina, {
mode: "no-cors"});
const resposta = await dados.json();
if (!resposta['status']) {
document.getElementById("msgAlerta").innerHTML = resposta['msg'];
} else {
const conteudo = document.querySelector(".listar-usuarios");
if (conteudo) {
conteudo.innerHTML = resposta['dados'];
}
}
}
listarUsuarios(1);
function editar_registro(COD) {
document.getElementById("botao_editar" + COD).style.display = "none";
document.getElementById("botao_salvar" + COD).style.display = "block";
var foto = document.getElementById("valor_foto" + COD);
var Nome_pet = document.getElementById("valor_Nome_pet" + COD);
var especie = document.getElementById("valor_especie" + COD);
var raca = document.getElementById("valor_raca" + COD);
var sexo = document.getElementById("valor_sexo" + COD);
var idade = document.getElementById("valor_idade" + COD);
var descricao = document.getElementById("valor_descricao" + COD);
foto.innerHTML = "<input type='file' id='fotoimagem" + COD + "' value='" + foto.innerHTML + "'>";
Nome_pet.innerHTML = "<input type='text' id='Nome_pet_text" + COD + "' value='" + Nome_pet.innerHTML + "'>";
especie.innerHTML = "<input type='text' id='especie_text" + COD + "' value='" + especie.innerHTML + "'>";
raca.innerHTML = "<input type='text' id='raca_text" + COD + "' value='" + raca.innerHTML + "'>";
sexo.innerHTML = "<input type='text' id='sexo_text" + COD + "' value='" + sexo.innerHTML + "'>";
idade.innerHTML = "<input type='text' id='idade_text" + COD + "' value='" + idade.innerHTML + "'>";
descricao.innerHTML = "<input type='text' id='descricao_text" + COD + "' value='" + descricao.innerHTML + "'>";
}
async function salvar_registro(COD) {
var Nome_pet_valor = document.getElementById("Nome_pet_text" + COD).value;
var especie_valor = document.getElementById("especie_text" + COD).value;
var raca_valor = document.getElementById("raca_text" + COD).value;
var sexo_valor = document.getElementById("sexo_text" + COD).value;
var idade_valor = document.getElementById("idade_text" + COD).value;
var descricao_valor = document.getElementById("descricao_text" + COD).value;
var foto_valor = document.getElementById("fotoimagem" + COD).value;
var dadosForm = "COD=" + COD + "&Nome_pet=" + Nome_pet_valor + "&especie=" + especie_valor + "&raca=" + raca_valor + "&sexo=" + sexo_valor + "&idade=" + idade_valor + "&descricao=" + descricao_valor + "&foto=" + foto_valor;
const dados = await fetch("editar.php", {
method: "POST",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: dadosForm
});
const resposta = await dados.json();
if (!resposta['status']) {
document.getElementById("msgAlerta").innerHTML = resposta['msg'];
} else {
document.getElementById("msgAlerta").innerHTML = resposta['msg'];
removerMsgAlerta();
document.getElementById("valor_Nome_pet" + COD).innerHTML = Nome_pet_valor;
document.getElementById("valor_especie" + COD).innerHTML = especie_valor;
document.getElementById("valor_raca" + COD).innerHTML = raca_valor;
document.getElementById("valor_sexo" + COD).innerHTML = sexo_valor;
document.getElementById("valor_idade" + COD).innerHTML = idade_valor;
document.getElementById("valor_descricao" + COD).innerHTML = descricao_valor;
document.getElementById("valor_foto" + COD).innerHTML = foto_valor;
document.getElementById("botao_editar" + COD).style.display = "block";
document.getElementById("botao_salvar" + COD).style.display = "none";
}
}
function removerMsgAlerta() {
setTimeout(function () {
// Substituir a mensagem
document.getElementById("msgAlerta").innerHTML = "";
}, 5000);
}`
Index.html
`<?php
include_once "conecta.php";
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row mt-4">
<div class="col-lg-12">
<div>
<h4>Listar Usuários</h4>
</div>
</div>
</div>
<hr>
<!-- SELETOR "msgAlerta" responsavel em receber a mensagem de sucesso ou erro -->
<span id="msgAlerta"></span>
<div class="row">
<div class="col-lg-12">
<!-- SELETOR "listar-usuarios" responsavel em receber os registros do banco de dados -->
<span class="listar-usuarios"></span>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script src="js/custom.js"></script>
</body>
</html>`
Conecta.php
`<?php
$host="localhost";
$port=3306;
$socket="";
$user="root";
$password="abcdefgh";
$dbname="Testecepet";
$conn = new mysqli($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());
?>`
MySQL Script
`create database Testecepet;
use Testecepet;
#Tabela do Animal
create table pet(COD integer PRIMARY KEY auto_increment NOT NULL,
foto longblob,
especie varchar(20) not null,
raca varchar(20) not null,
sexo varchar(20) not null,
idade varchar(20) not null,
Nome_pet varchar(50) not null,
descricao varchar(1000));
`
I'm parsing JSON feed from the blogger API but its throwing following error:
37:59 Uncaught TypeError: Cannot read property 'url' of undefined
Previously it was working fine, there weren't any issues but suddenly the error keeps coming up and nothing is displaying. I have looked for stackoverflow and followed this post as well but the error is not going away. Maybe blogger has changed their object nodes that i can't figure out.
Javascript Code:
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/');
var postTimestamp = json.feed.entry[i].published.$t;
var item = '<div class="col-md-3 mb-4 blogpost-main">';
var item = item + '<div class="card h-100">';
var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
var item = item + '<div class="card-body">';
var item = item + '' + postTitle + '</h6>';
var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= '+ postTimestamp +'>' + postTimestamp + '</time></p>';
var item = item + '</div>';
var item = item + '</div>';
var item = item + '</div>';
//document.write(item);
document.getElementById("news").appendChild(item);
console.log(item);
}
}
</script>
<script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>
<div id="news"></div>
JsFiddle: https://jsfiddle.net/645pg9rz/
If you run console.log(json.feed.entry) in your fiddle, you'll see that there is no key called media$thumbnail in the returned objects. That is why your code is failing at var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/'); - it is trying to access the url property of an item that doesn't exist.
Perhaps the API used to use that key and no longer does, or there are just no thumbnails available in the entries you requested. I don't see a new key with an image file other than the Blogger logo.
Updated: the pictures you're trying to reach are not in the object that came to you. that's why you get the error. (json.feed.entry[i].media$thumbnail)
there are no pictures in the object that came to you. It's the only icon that comes. I put them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Document</title>
<style>
</style>
</head>
<body>
<div class="row" id="news"></div>
<script>
function mycallback(json) {
console.log(json)
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0, 400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].author[0].gd$image.src;
var postTimestamp = json.feed.entry[i].published.$t;
console.log(postImage)
var item = '<div class="col-md-3 mb-4 blogpost-main">';
var item = item + '<div class="card h-100">';
var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
var item = item + '<div class="card-body">';
var item = item + '' + postTitle + '</h6>';
var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= ' + postTimestamp + '>' + postTimestamp + '</time></p>';
var item = item + '</div>';
var item = item + '</div>';
var item = item + '</div>';
document.getElementById("news").innerHTML += item;
}
}
</script>
<script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>
</body>
</html>
This is my Javascript code I have so far. I am trying to create a personInfo() object with 2 functions. I am not sure what I am doing wrong.
var personInfo =
{
personInfo.personRelation: " ",
personInfo.personName: " ",
personInfo.personAge: 0,
personInfo.personGender: " "
var relationValue = personRelation;
var nameValue = personName;
var ageValue = personAge;
var genderValue = personGender;
getPersonInfo: function()
{
document.write( "<p>" + personInfo.personRelation + "<br />" );
document.write( "Name: " + personInfo.personName + "<br />");
document.write( "Age: " + personInfo.personAge + "<br />" );
document.write( "Gender: " + personInfo.personGender + "</p>" );
}
setPersonInfo(relationValue, nameValue, ageValue, genderValue): function()
{
this.relationValue = relationValue;
this.nameValue = nameValue;
this.ageValue = ageValue;
this.genderValue = genderValue;
}
}; // end object personInfo
This my html code...I am trying to print each object with the while loop. I am very new to Javascript, so I am not sure if I mistakes in the external javascript file or if it is simply my implementation. Any help would be great. Thank you.
<html>
<head>
<link rel="stylesheet" href="object.css" type ="text/css" />
<title>Object Test</title>
<script type="text/javascript" src="MyObject.js">
var people = new Array(5);
</script>
</head>
<body>
<script type="text/javascript" src="MyObject.js">
var dad_info = setPersonInfo("Dad", "Kenneth Vavrock", 66, "Male");
dad_info = people[0];
var mom_info = setPersonInfo("Mom", "Connie Vavrock", 63, "Female");
mom_info = people[1];
var brother_info = setPersonInfo("Brother", "Craig Vavrock", 33, "Male");
brother_info = people[2];
var nephew_info = setPersonInfo("Nephew", "Sawyer Vavrock", 1, "Male");
nephew_info = people[3];
var dad_info = setPersonInfo("Step Mother", "Bonnie Vavrock", 70, "Female");
stepmother_info = people[4];
var count = 1;
while ( count >= 0 )
{
dad_info.getPersonInfo();
mom_info.getPersonInfo();
brother_info.getPersonInfo();
nephew_info.getPersonInfo();
stepmother_info.getPersonInfo();
count--;
}
</script>
</body>
</html>
Your "personInfo" object is malformed, it looks like a mix between a object literal and a class-like function. Have a look at this tutorial
Also, do not use an empty string " " as default value for anything (unless you really need to), there is really no point to it.
To solve the problem at hand.
var personInfo = function () {
this.personRelation = "";
this.personName = "";
this.personAge = 0;
this.personGender = "";
this.getPersonInfo = function () {
document.write( "<p>" + personInfo.personRelation + "<br />" );
document.write( "Name: " + personInfo.personName + "<br />");
document.write( "Age: " + personInfo.personAge + "<br />" );
document.write( "Gender: " + personInfo.personGender + "</p>" );
}
};
This way it can be used as such:
var people = []; // Create an empty array
// Create new person info for "dad"
var dad_info = new personInfo();
dad_info.personRelation = "...";
// [...]
people.push(dad_info); // Add dad_info to the array.
You should be all set.
I am trying to load jQuery tablesorter in a customized infowindow generated by cartodb.js. The idea is that when I click a data point on the map an infowindow will open, loading data dynamically from the database. While the information is loaded correctly and displayed as an ordinary table, the tablesorter is not loaded.
The relevant code:
<script>
$(document).ready(function()
{
$("#bewohner").tablesorter();
}
);
</script>
<script type="infowindow/html" id="infowindow_template">
<div class="infowindow-custom">
x
<div class="cartodb-tooltip-content-wrapper">
<div class="cartodb-tooltip-content" style="padding:2px">
<div id="strasse"></div>
<table id="bewohner" class='tablesorter table table-condensed'>
<thead>
<tr>
<th>
<th>Familienname
<th>Vorname
<th>Beruf</th>
<th>Etage</th>
<th>Tel.</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div class="cartodb-tooltip-container"></div>
</div>
</script>
....
cartodb.createLayer(map, layerUrl, layerOptions)
.addTo(map)
.on('done', function(layer) {
var infowindow = layer.getSubLayer(0).infowindow
infowindow.set('template', function(data) {
var clickPosLatLng = this.model.get('latlng');
var fields = this.model.get('content').fields;
if (fields && fields[0].type !== 'loading') {
var obj = _.find(fields, function(obj) {
return obj.title == 'strasse_original'
}).value
} // end test of status
$.get("http://******.cartodb.com/api/v1/sql?q=select * from vauban_1 where strasse_original= '" + obj + "' ORDER BY etage, familienname ASC", function(data) {
$('#strasse').append("<h4>" + data.rows[0].strasse_heute + " / " + data.rows[0].strasse_original +"</h4>");
for (var i = 0; i < data.total_rows; i++) {
$('#bewohner tbody').append("<tr><td>" + data.rows[i].zusatz + "<td>" + data.rows[i].familienname + "<td>" + data.rows[i].vorname + "<td>" + data.rows[i].beruf + "<td>" + data.rows[i].etage + "<td>" + data.rows[i].telefon + "</td></tr>");
}
});
return $('#infowindow_template').html();
});
})
It seems that I somehow have to trigger the tablesorter each time the infowindow is loaded, but I don't know how.
I the call for tablesorter was not placed correctly, as it has to be placed inside the function that updates the infowindow. Thus, a working version of the function is:
cartodb.createLayer(map, layerUrl, layerOptions)
.addTo(map)
.on('done', function(layer) {
var infowindow = layer.getSubLayer(0).infowindow
infowindow.set('template', function(data) {
var clickPosLatLng = this.model.get('latlng');
var fields = this.model.get('content').fields;
if (fields && fields[0].type !== 'loading') {
var obj = _.find(fields, function(obj) {
return obj.title == 'strasse_original'
}).value
} // end test of status
$.get("http://******.cartodb.com/api/v1/sql?q=select * from vauban_1 where strasse_original= '" + obj + "' ORDER BY etage, familienname ASC", function(data) {
$('#strasse').append("<h4>" + data.rows[0].strasse_heute + " / " + data.rows[0].strasse_original +"</h4>");
for (var i = 0; i < data.total_rows; i++) {
$('#bewohner tbody').append("<tr><td>" + data.rows[i].zusatz + "<td>" + data.rows[i].familienname + "<td>" + data.rows[i].vorname + "<td>" + data.rows[i].beruf + "<td>" + data.rows[i].etage + "<td>" + data.rows[i].telefon + "</td></tr>");
}
$("#bewohner").tablesorter();
});
return $('#infowindow_template').html();
});
})
I have created dynamically some select controls(a.k.a. groupbox) but every time that I try to access to one of them if get the followig error:
Uncaught TypeError: undefined is not a function
Here is the code:
var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();
Where parseInt(buttonElementId + 1 is always a number so the error is not there
<html>
<head lang="en">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<style>
body { padding-top:80px; }
html, body, #wrapper
{
width: 100%;
height: 100%;
}
</style>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="container">
<div id="information"></div>
<div id="tableInformation"></div>
<div id="goBack"></div>
<br/>
<div id="inputDiv"></div>
<br/>
<br/>
<div id="UserGuide"></div>
</div>
<script src="js/jquery-1.11.js"> </script>
<script>
var apiUrl = 'http://localhost/devices';
$( document ).ready(function() {
// Handler for .ready() called.
jsonGETRequest(apiUrl, jsonExampleData);
});
$(document).on('click', ':button' , function() {
// reference clicked button via: $(this)
$("#UserGuide").empty();
var buttonElementId = $(this).attr('id');
if(buttonElementId.indexOf("btnShowFunc") > -1) {
buttonElementId = buttonElementId.replace("btnShowFunc","");
deviceUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) + 1)].cells[1].innerHTML;
goBack = "firstAPIRequest";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
} else if(buttonElementId.indexOf("btnGoBack") > -1 ) {
switch (goBack) {
case "firstAPIRequest":
goBack = "";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl, jsonExampleData);
removeGoBackInputDiv();
break;
case "secondAPIRequest":
goBack = "firstAPIRequest";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
removeGoBackInputDiv();
break;
}
}else if(buttonElementId.indexOf("btnRunFunc") > -1) {
goBack = "secondAPIRequest";
buttonElementId = buttonElementId.replace("btnRunFunc","");
var functionUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) +1)].cells[2].innerHTML;
var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();
$("#tableInformation tbody").remove();
$("#inputDiv").empty();
// /jsonPOST(apiUrl '/functions/' + functionUID )
}
});
function loadDataIntoDeviceGrid(jsonData) {
//$("#tableInformation").addClass("table table-responsive table-bordered");
var tbl=$("<table/>").attr("id","mytable");
$("#tableInformation").append(tbl);
$("#mytable").append("<tr>" + "<th>dal.device.status</th>" + "<th>dal.device.UID</th>"
+ "<th>dal.device.driver</th>" + "<th>service.id</th>" +"<th></th>" + "</tr>");
for(var i=0;i<jsonData.length;i++)
{
var tr = "<tr>";
var td1 = "<td>"+jsonData[i]["dal.device.status"]+"</td>";
var td2 = "<td>"+jsonData[i]["dal.device.UID"]+"</td>";
var td3 = "<td>"+jsonData[i]["dal.device.driver"]+"</td>";
var td4 = "<td>"+jsonData[i]["service.id"]+"</td>";
//#Deprecated var dataList = fillSelectControl(jsonData[i]["objectClass"]); #Deprecated
var btn = "<td>" + "<button id='btnShowFunc"+ i + "' class='btn btn-success btn-lg'>See function</button>" + "</td></tr>";
$("#mytable").append(tr + td1 + td2 + td3 + td4 + btn );
}
$("#mytable").addClass("table table-responsive table-bordered");
}
function loadInformationDeviceGrid() {
$("#UserGuide").addClass("alert alert-info");
$("#UserGuide").html("<h3>Getting devices list:</h3><br/> "+
"Using this request, you can retrieve a list of all the available devices."+
"For every device, among other info, there is the indication of the device unique ID, which" +
"can be used to directly access to the device and the indication of the device driver (ZigBee, Bluetooth, etc.).<br/>If you want see some request response example please visit this <a href='#'>site</a>");
}
function removeGoBackInputDiv() {
$("#inputDiv").empty();
$("#btnGoBack").remove();
}
function loadDataIntoFunctionsGrid(jsonData) {
$("#mytable").append("<tr>" + "<th>function.device.UID</th>"
+ "<th>service.id</th>" + "<th>function.UID</th>" + "<th>operation.names</th>" + "<th></th>" + "</tr>");
var tr, td2, td3, td4, dt2, btn;
for(var i = 0; i < jsonData.length; i++) {
tr = "<tr>";
//#Deprecated td1 = "<td>" + jsonData[i]["CLASS"] + "</td>";
td2 = "<td>" + jsonData[i]["al.function.device.UID"] + "</td>";
td3 = "<td>" + jsonData[i]["service.id"] + "</td>";
td4 = "<td>" + jsonData[i]["dal.function.UID"] + "</td>";
//#Deprecated dt1 = fillSelectControl(jsonData[i]["objectClass"]);
dt2 = fillSelectControl(jsonData[i]["dal.function.operation.names"], i);
btn = "<td>" + "<button id='btnRunFunc"+ i + "' class='btn btn-success btn-lg'>Run</button>" + "</td></tr>";
$("#mytable").append(tr + td2 + td3 + td4 + dt2 + btn );
}
createGoBackButton();
createInputTextParameters();
}
function loadInformationFunctionsGrid() {
$("#UserGuide").addClass("alert alert-info");
$("#UserGuide").html("<h3>Getting device functions:</h3><br/>"
+ "This API is used to retrieve the list of the available functions supported by the device. For"
+ "example a Smart Plug has two functions: one to retrieve the energy consumption and another"
+ "'boolean' function useful to change the status of the smart plug (ON/OFF). Every function"
+ "indicates the id, which can be used to access directly the function and the list of the operation"
+ "that can be invoked on the function.<br/>"
+ "P.S. If he want use a function that want some parameters he must write these into the dedicated textbox. If the API needs more parameters separate these using comma. <br/>"
+ "Example of parametes: <br/> <code>'type':'java.math.BigDecimal'</code><br/> <code>'value':1</code> <br/> etc...");
}
function createGoBackButton() {
var btn = '<button id="btnGoBack" class="btn btn-warning btn-lg">Go Back</button>';
$("#goBack").append(btn);
}
function createInputTextParameters() {
var lbl ="<label>Paramters</label>";
var txt ='<input type="text" class="form-control" name="email">';
$("#inputDiv").addClass("form-group");
$("#inputDiv").append(lbl);
$("#inputDiv").append(txt);
}
function fillSelectControl(obj, id) {
var dataList = "<td><select id='slt"+ id +"'>";
for(var j = 0; j < obj.length; j++)
dataList = dataList + "<option value='" + obj[j] + "'>" + obj[j] + "</option>";
return dataList = dataList + "</select></td>";
}
var json = "";
var goBack = "";
var deviceUID;
function jsonGETRequest(url, dataExample){
$.getJSON(apiUrl, function(data) {
alert(JSON.stringify(data));
this.json = data;
})
.done(function() {
$("#information").addClass("alert alert-success");
$("#information").text("getJSON request succeeded!");
if(goBack == "") {
loadDataIntoDeviceGrid(jsonExampleData);
loadInformationDeviceGrid();
} else if (goBack=="firstAPIRequest") {
loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
loadInformationDeviceGrid();
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
//alert('getJSON request failed! ' + textStatus);
$("#information").addClass("alert alert-danger");
$("#information").text("Impossible get data from API, it will be use example data" + errorThrown);
if(goBack == "") {
loadDataIntoDeviceGrid(jsonExampleData);
loadInformationDeviceGrid();
} else if (goBack=="firstAPIRequest") {
loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
loadInformationFunctionsGrid();
} else if(goBack=="secondAPIRequest") {
}
})
.always(function() { });
}
function jsonPOST(url, method, paramters, dataExample) {
}
var jsonExampleData = [
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test123",
"dal.device.driver": "ZigBee",
"service.id": 28,
"objectClass": [
"org.osgi.service.dal.Device"
]
},
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test456",
"dal.device.driver": "ZigBee",
"service.id": 29,
"objectClass": [
"org.osgi.service.dal.Device"
]
},
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test789",
"dal.device.driver": "ZigBee",
"service.id": 30,
"objectClass": [
"org.osgi.service.dal.Device"
]
}
];
var jsonExampleDataFunctions = [
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test123",
"service.id": 27,
"dal.function.UID": "ZigBee:test123:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
},
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test456",
"service.id": 26,
"dal.function.UID": "ZigBee:test456:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
},
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test789",
"service.id": 25,
"dal.function.UID": "ZigBee:test789:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
}
];
</script>
</body>
</html>
.is() returns a true/false value, it does not continue the jQuery chain, therefor there is no .text() function to call
As DevishOne points out in the comments to get the selected option's text do:
=$("#slt" + (parseInt(buttonElementId + 1))).children("option:selected").text();
Split that in to multiple steps and check for the particular result:
button = $("#slt" + (parseInt(buttonElementId + 1)));
if ( button )
{
childs = button.children("option");
if ( childs .....
Whenever there's no option selected, you are unable to catch that since you refer directly to a method .text() of null.