I'm trying to develope an event on JavaScript in a WordPress page that after clicking a href can display a colum but I have this error:
Uncaught TypeError: Cannot read property 'style' of undefined
at show_hide_column ((index):212)
at HTMLAnchorElement.onclick
The code which I have for the script is:
function show_hide_column(col_no, do_show) {
alert(col_no);
var stl;
if (do_show)
stl = 'block'
else
stl = 'none';
var tbl = document.getElementById('id_of_table');
var rows = tbl.getElementsByTagName('tr');
for (var row = 0; row < rows.length; row++) {
var cels = rows[row].getElementsByTagName('td')
cels[2].style.display = stl;
}
}
Html:
<table id="id_of_table" width="966">
<tbody>
<tr>
<td colspan="3" width="966"><strong>POLITICA DE PRIVACIDAD </strong></td>
</tr>
<tr>
<td width="187"><strong> </strong></td>
<td width="227"><strong>1ª CAPA - Información básica</strong></td>
<td width="553"><strong>2ª CAPA- Información adicional</strong></td>
</tr>
<tr>
<td width="187"><strong>RESPONSABLE</strong></td>
<td width="227"><a href="#" onClick='javascript:show_hide_column(2, false);'>RED S.L.</a></td>
<td width="553">
La entidad encargada de atender todas las cuestiones relativas al tratamiento de los datos de carácter personal en relación al uso de la APLICACIÓN será RED S.L. (en adelante “LA EMPRESA”). En este sentido, se indican los siguientes datos de contacto:
</td>
</tr>
</table>
What happen with this error?. Thanks so much
The error coming from the first tr since it only have one td. You can separate the top tr and the other with thead and tbody, then only loop the tbody.
Another tip, you can change this:
var stl;
if (do_show)
stl = 'block'
else
stl = 'none';
To this:
var stl = (do_show) ? 'block' : 'none';
Related
I was trying to give a data-attribute to an element, them getting by id that element and try to access to data, but without success, Maybe its related to the way is displayed the HTML, I mean:
<div class="col-md-2 col-sm-12 col-xs-12 ">
<table>
<thead>
Servicios
<tr>
#foreach (var feature in hotel.Features.Take(6)) {
<!-- DATA-* LISTA SERVICIOS-->
<td class="col-md-6 showTruncateText" id="serviciosHotel" data-listServices="#feature.Code">
#feature.Description
</td>
<!--Esta pieza hace que se genere filas con 3 elementos. Una vez llega al
tercero, empieza otra fila.-->
if (counter % 2 == 0) { #:
</tr>
<tr>
} counter++; }
</tr>
</thead>
</table>
</div>
This is my html code and this is how its rendered:
<div class="col-md-2 col-sm-12 col-xs-12 ">
Servicios
<table>
<thead>
<tr>
<!-- DATA-* LISTA SERVICIOS-->
<td class="col-md-6 showTruncateText" id="serviciosHotel" data-listservices="APCO">
Aptos./Hab. con cocina
</td>
<!--Esta pieza hace que se genere filas con 3 elementos. Una vez llega al
tercero, empieza otra fila.-->
<!-- DATA-* LISTA SERVICIOS-->
<td class="col-md-6 showTruncateText" id="serviciosHotel" data-listservices="CAFE">
Cafetería
</td>
<!--Esta pieza hace que se genere filas con 3 elementos. Una vez llega al
tercero, empieza otra fila.-->
</tr>
<tr>
<!-- DATA-* LISTA SERVICIOS-->
<td class="col-md-6 showTruncateText" id="serviciosHotel" data-listservices="CFTE">
Caja fuerte individual
</td>
<!--Esta pieza hace que se genere filas con 3 elementos. Una vez llega al
tercero, empieza otra fila.-->
<!-- DATA-* LISTA SERVICIOS-->
<td class="col-md-6 showTruncateText" id="serviciosHotel" data-listservices="ITNS">
Punto de Internet
</td>
<!--Esta pieza hace que se genere filas con 3 elementos. Una vez llega al
tercero, empieza otra fila.-->
</tr>
<tr>
<!-- DATA-* LISTA SERVICIOS-->
<td class="col-md-6 showTruncateText" id="serviciosHotel" data-listservices="JARD">
Jardines /Terraza
</td>
<!--Esta pieza hace que se genere filas con 3 elementos. Una vez llega al
tercero, empieza otra fila.-->
<!-- DATA-* LISTA SERVICIOS-->
<td class="col-md-6 showTruncateText" id="serviciosHotel" data-listservices="JUEG">
Parque infantil
</td>
<!--Esta pieza hace que se genere filas con 3 elementos. Una vez llega al
tercero, empieza otra fila.-->
</tr>
<tr>
</tr>
</thead>
</table>
</div>
So far here, everything ok, but in the js part is where I am getting the wrong answers, I mean I have tried a lot of ways but the most closer I get was null and undefined.
var dataServicios = document.querySelector('serviciosHotel').dataset;
for (var i in dataServicios) {
console.log(i, dataServicios[i])
};
var listaServicios = document.getElementById('serviciosHotel');
var listaServicios2 = listaServicios.getAttribute('data-listservices');
console.log(listaServicios2);
var dataServicios2 = document.getElementById("serviciosHotel");
var nombreServicio = dataServicios2.dataset.listServices;
console.log(nombreServicio);
var serviciosdelhotel = document.getElementById("serviciosHotel");
var ratings = serviciosdelhotel.getAttribute("data-listServices");
console.log(ratings);
JQUERY
var servicioshotelenrique = $("#serviciosHotel");
var owner = servicioshotelenrique.data("listServices");
console.log(owner);
var dataServicios = $('#serviciosHotel').data();
for (var i in dataServicios) {
$('<li>', {
text: i + ': ' + data[i]
}).appendTo('#out');
}
console.log(dataset(document.getElementById('serviciosHotel')[0]));
$("#serviciosHotel").click(function () {
var id = $(this).attr('data-listServices');
console.log(id);
});
console.log($("#serviciosHotel").data("listServices"));
What I am doing wrong?? its first time I work with data-attributes and isn´t supose to be difficult but...you know I cannot see clear.
Thank you very much!!
Watch your capitals. Data attributes are case sensitive.
console.log($("#serviciosHotel").data("listServices"));
Should be
console.log($("#serviciosHotel").data("listservices"));
Then it works.
According to me, you're writing way too much JS code to retrieve data that come from your back-end model (or maybe the hotel variable is an injected service?).
Considering the data are coming from your back-end model, a nice workaround would be to write the code below in your CSHTML file.
<script>
var model = #Html.Raw(Json.Serialize(Model));
</script>
If your JS is in a separate file, you could store the data in a hidden HTML element.
You could also put your JS code in a JS class, and inject the data in the constructor parameters, like this:
<script>
var view = new NameOfTheViewClass(#Html.Raw(Json.Serialize(Model)));
view.init();
</script>
i have to html files 1st is a table with a boton in the last column, the 2nd is a html file with an image so i need to clic the table row and print this values over the secont html file, is a certificate with values has name and chronometer time, the finale objetive is to print in pdf but now i am trying to move table row data to the certificate.
thnaks a lot for help
this si the code i try on firts html file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script>
// function myFunction() {
// var myWindow = window.open("", "", "width=600,height=400");
// myWindow.document.write("valores+=$(this).html()+"\n");
// var valores="";
// $(this).parents("tr").find("td").each(function(){
// valores+=$(this).html()+"\n";
// });
// });
$(document).ready(function() {
$(".boton").click(function() {
var myWindow = window.open("cert.html", "_blank", "width=1090,height=860");
var valores = "";
// Obtenemos todos los valores contenidos en los <td> de la fila
// seleccionada
$(this).parents("tr").each(function() {
valores += $(this).html() + "\n";
//valores = valores + "</br></br>";
});
// myWindow.document.write(valores+ "<body background='plantilla.png'/>");
// myWindow.document.write("<span class='green'>The score you entered is:" + valores + ".Your letter grade is: B!</span>");
myWindow.document.write(valores);
// myWindow.document.write(valores);
// alert(valores);
});
});
</script>
<style>
myWindow {
background-image: url("cedulalmma.jpg");
}
.boton {
border: 1px solid #808080;
cursor: pointer;
padding: 2px 5px;
color: white;
}
</style>
<table border="1" cellspacing="2" cellpadding="5">
<tr>
<td>val 1</td>
<td>val 2</td>
<td>val 3</td>
<td class="boton"></td>
</tr>
<tr>
<td>val 4</td>
<td>val 5</td>
<td>val 6</td>
<td class="boton"></td>
</tr>
<tr>
<td>val 7</td>
<td>val 8</td>
<td>val 9</td>
<td class="boton"></td>
</tr>
</table>
Here is one way to do it.
Modify your table script like this:
<script>
$(document).ready(function() {
$(".boton").click(function() {
var valores = "";
// $(this).siblings() retrieves every adjacent td of the current one
$(this).siblings().each(function() {
valores += $(this).html() + "\n";
//valores = valores + "</br></br>";
});
var myWindow = window.open("cert.html", "_blank", "width=1090,height=860");
// Here You assing the values to a window property:
myWindow.valores = valores;
});
});
</script>
Then, in your second HTML page, load jQuery and you could get the values like this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
// Here you can manipulate the however you like
console.log(window.valores);
});
</script>
If the server needs to parse the file (because it needs a key or something that only the server has), then You need to send the data to it using POST, as You can see here.
Hope it helps.
This question already has answers here:
JavaScript .replace only replaces first Match [duplicate]
(7 answers)
Closed 4 years ago.
I have an array containing words that need to be styled if found in a string, but I'm struggling to make it work correctly.
Here is my code, as you can see I'm looping both the array and the table containing my strings.
in the first string, only 1 word (venkel) is being picked up and replaced but only once also. I need all the words in the array to be replaced if found in the strings by bold values.
UPDATE when using Regex, not every words update
var productName = ["witte asperges", "crème fraîche", "wijtingfilet", "selder", "BIO wortelen", "BIO rode ui", "venkel"],
descriptionName = document.getElementsByClassName("Description");
for (var i = 0; i < productName.length; i++) {
var product = productName[i];
for (var x = 0; x < descriptionName.length; x++) {
var description = descriptionName[x];
if (description.textContent.indexOf(product) !== -1) {
descriptionName[x].innerHTML = descriptionName[x].textContent.replace(product, product.bold());
}
}
}
<table style="width:60%;">
<tbody>
<tr>
<td class="data Description">Spoel ondertussen de wortelen goed schoon en snijd de wortelen en de selder in blokjes van 2 cm. Verwijder het stugge uiteinde van de venkel en snijd in plakjes van 2 cm. Voeg de venkel, de wortelen en de selder toe aan de pan en laat 4 min.</td>
</tr>
<tr>
<td class="data Description">Spoel de aardappelen en boen ze goed schoon. Snijd ze in blokjes van 3 cm en kook ze in zo’n 10-15 min. beetgaar in lichtgezouten water.</td>
</tr>
<tr>
<td class="data Description">Giet de crème fraîche bij het vispannetje, breng op smaak met een snuifje zout en flink wat zwarte peper en laat 3 min. opwarmen. Dien het vispannetje op met de puree. Smakelijk!</td>
</tr>
</tbody>
</table>
Use a regular expression for the global replace on your product variable like this:
new RegExp(product,"g");
You also need to change the code to descriptionName[x].innerHTML = descriptionName[x].innerHTML.replace(reg, product.bold()); for changing the HTML content and not the text content with bold.
WORKING EXAMPLE
var productName = ["witte asperges", "crème fraîche", "wijtingfilet", "selder", "BIO wortelen", "BIO rode ui", "venkel"],
descriptionName = document.getElementsByClassName("Description");
for (var i = 0; i < productName.length; i++) {
var product = productName[i];
for (var x = 0; x < descriptionName.length; x++) {
var description = descriptionName[x];
if (description.textContent.indexOf(product) !== -1) {
var reg = new RegExp(product,"g");
descriptionName[x].innerHTML = descriptionName[x].innerHTML.replace(reg, product.bold());
}
}
}
<table style="width:60%;">
<tbody>
<tr>
<td class="data Description">Spoel ondertussen de wortelen goed schoon en snijd de wortelen en de selder in blokjes van 2 cm. Verwijder het stugge uiteinde van de venkel en snijd in plakjes van 2 cm. Voeg de venkel, de wortelen en de selder toe aan de pan en laat 4 min.</td>
</tr>
<tr>
<td class="data Description">Spoel de aardappelen en boen ze goed schoon. Snijd ze in blokjes van 3 cm en kook ze in zo’n 10-15 min. beetgaar in lichtgezouten water.</td>
</tr>
<tr>
<td class="data Description">Giet de crème fraîche bij het vispannetje, breng op smaak met een snuifje zout en flink wat zwarte peper en laat 3 min. opwarmen. Dien het vispannetje op met de puree. Smakelijk!</td>
</tr>
</tbody>
</table>
When I try to convert a html page to pdf with jsPDF it return a blank page and if I debug with firedebug that return a error
link to jsfiddle
TypeError: headers[j] is undefined on jspdf.debug.js (linea 3329, col 5)
rowData[headers[j].name] =tableRow.cells[j].textContent.replace(/\r?\n/g, '');
that is the html code of the page
<table>
<tbody><tr>
<td rowspan="2" class="logo"><img class="logoimg" src="images/logo_APRIE.png" alt="logo aprie"></td>
<td colspan="3" class="verde altro">Questionario rivolto ai gestori di
impianti di produzione di energia <br>alimentati con fonti
rinnovabili, anche in modo non esclusivo
</td>
</tr>
<tr>
<td class="annorif"><b>Anno di riferimento:</b></td>
<td class="giallo anno">2015</td>
<td class="altro"> </td>
</tr>
<tr>
<td colspan="4" class="altro"><b>I dati sono dovuti ai termini del comma 3 dell'art.
7 della LEGGE PROVINCIALE 4 ottobre 2012, n. 20:</b><br> <br> <i>I
soggetti pubblici e privati che esercitano sul territorio
provinciale attività energetiche soggette a concessione,
autorizzazione o altro titolo comunque denominato, o che realizzano
progetti finanziati con contributi provinciali, devono fornire
all'osservatorio provinciale dell'energia le informazioni, i dati e
i documenti, se richiesti, per l'esercizio dei compiti e delle
attività previste da questa legge.</i><br> <br> <b>e del punto 6
della Delibera della Giunta Provinciale n. 1826 del 27 Ottobre 2014<br>
<br> Per eventuali dubbi o chiarimenti si prega di contattare presso
APRIE il dott. john doe (0123-456789 -
john.doe#prova.it)
</b></td>
</tr>
<tr>
<td colspan="4" class="altro"><b>Avvertenze:</b></td>
</tr>
<tr>
<td colspan="4" class="altro">- il questionario è rivolto ai gestori di impianti di
produzione di energia (inclusi gli impianti di teleriscaldamento) che
utilizzano anche, o esclusivamente, fonti rinnovabili.</td>
</tr>
<tr>
<td colspan="4" class="altro">- nel caso una società gestisca più impianti o un
sistema complesso composto da più reti</td>
</tr>
<tr>
<td colspan="2" class="giallo altro"><b>- compilare solo le celle di colore
giallo compatibili con la tipologia d'impianto</b></td>
<td colspan="2" class="required altro"><b>- I campi con bordo di colore
blue sono obbligatorie</b></td>
</tr>
</tbody></table>
and the script for calling jspdf is
<script>
$(function() {
var doc = new jsPDF('p', 'pt', 'letter');
var dochtml=$(\"#questionario\").html();
$(dochtml).find(\"script\").remove();
console.log (dochtml);
// We'll make our own renderer to skip this editor
// All units are in the set measurement for the document
// This can be changed to \"pt\" (points), \"mm\" (Default), \"cm\", \"in\"
doc.fromHTML(dochtml);
doc.save('prova_quest.pdf');
});
</script>
the thing here is, i have this code, and it was supposed to output the results of the variables into contact form 7 for wordpress hidden fields (i have the modules plugin to enable the hidden fields) that were sent by email, but i dont think the id i display is getting the value i attribute, i js linted the code and all it said was multiple variable declaration, which shouldnt be a problem since it's an if statement, so, there will never be a double declaration of the variable.
This is the code i use to transform the cookies created in my script (using jQuery.cookie) into text that is outputted to a table in my website, but more than outputting it to a table, i would like to email it to the user, i already have a contact-form 7 form prepared to do this, i just need to attribute the value of the returned variable (or at least one of them, the last is the price, i dont need to send that by email) to the contact form field id, yesterday here in stackoverflow someone gave me that code to pass the value into contact form 7, but im afraid it isnt working :/
function readRims() {
var rims_read = $.cookie('rim_color');
if (rims_read=="black" ) {
var jantes = 'Pretas';
var preco = 'Sob Consulta';
}
else if (rims_read=="silver"){
var jantes = 'De Série';
var preco = '';
}
else if (rims_read=="white"){
var jantes = 'Brancas';
var preco = 'Sob Consulta';
}
else if (rims_read=="titanium"){
var jantes = 'Titanium';
var preco = 'Sob Consulta';
}
else {
var jantes = 'Escolha as Jantes';
var preco =' ';
}
$('#cfg_rims').val(jantes);
return {
jantes: jantes,
preco: preco
};
}
HTML
[hidden modelo id:cfg_model]
[hidden cor id:cfg_color]
[hidden jantes id:cfg_rims]
[hidden ac id:cfg_ac]
[hidden abs id:cfg_abs]
[hidden alarme id:cfg_alarm]
[hidden led id:cfg_led]
[hidden chapeleira id:cfg_chapeleira]
<p>Oferecemos a possibilidade de enviar um email à nossa equipa com as suas escolhas no nosso configurador como manifestação de interesse, preencha o seguinte formulário e carregue em enviar para proceder ao envio da informação, a nossa equipa entrará em contacto consigo para dar seguimento à manifestação de interesse.</p>
<p>O seu Nome<br/></p>
[text* nome]
<p>O seu Email<br/></p>
[email* email]
<p>Observações<br/></p>
[textarea obs]
<p>[submit "Enviar"]</p>
Try
<table class="tab_cfg" align="center" width="70%" cellspacing="0"
cellpadding="10">
<tr style="border-bottom: none;">
<th colspan="4"><br />
<p>Abra o Configurador e siga todos os passos, a tabela abaixo
vai mostrar os resultados que escolheu:</p></th>
</tr>
<tr>
<th colspan="4"><a class="readon"
href="http://popo.com.pt/POPO/configurador/cfg/page_model/configurador_model.html"
rel="rokbox[550 600]">Configurador</a> <a class="readon"
href="javascript:setCookies(); document.location.reload(true)">Reset</a>
</th>
</tr>
<tr>
<td colspan="2"> </td>
<td>Característica</td>
<td>Preço</td>
</tr>
<tr>
<td colspan="2">Modelo</td>
<td><p class="modelo-modelo"></p></td>
<td><p class="modelo-preco"></p></td>
</tr>
<tr>
<td colspan="2">Cor</td>
<td><p class="color"></p></td>
<td></td>
</tr>
<tr>
<td colspan="2">Jantes</td>
<td><p class="rims-jantes"></p></td>
<td><p class="rims-preco"></p></td>
</tr>
<tr>
<td style="border-right: 1px solid #d1d1d1;" rowspan="6">Extras</td>
<td>ABS</td>
<td><p class="abs-abs"></p></td>
<td><p class="abs-preco"></p></td>
</tr>
<tr border="1px">
<td>Ar Condicionado</td>
<td><p class="ac-ac"></p></td>
<td><p class="ac-preco"></p></td>
</tr>
<tr>
<td>Alarme</td>
<td><p class="alarm-alarm"></p></td>
<td><p class="alarm-preco"></p></td>
</tr>
<tr>
<td>Luzes LED</td>
<td><p class="led.led"></p></td>
<td><p class="led.preco"></p></td>
</tr>
<tr style="border-bottom: none;">
<td>Chapeleira</td>
<td><p class="chapeleira-chapeleira"></p></td>
<td><p class="chapeleira-preco"></p></td>
</tr>
</table>
<script type="text/javascript">
jQuery(function($) {
var $table = $('.tab_cfg');
var modelo = readModel();
$table.find('.modelo-modelo').html(modelo.modelo)
$table.find('.modelo-preco').html(modelo.preco)
$table.find('.color').html(readColor())
var jantes = readRims();
$table.find('.rims-jantes').html(jantes.modelo)
$table.find('.rims-preco').html(jantes.preco)
var abs = readABS();
$table.find('.abs-abs').html(abs.modelo)
$table.find('.abs-preco').html(abs.preco)
var ac = readAC();
$table.find('.ac-modelo').html(ac.modelo)
$table.find('.ac-preco').html(ac.preco)
var alarm = readAlarm();
$table.find('.alarm-modelo').html(alarm.modelo)
$table.find('.alarm-preco').html(alarm.preco)
var led = readLED();
$table.find('.led-modelo').html(led.modelo)
$table.find('.led-preco').html(led.preco)
var chapeleira = readChap();
$table.find('.chapeleira-modelo').html(chapeleira.modelo)
$table.find('.chapeleira-preco').html(chapeleira.preco)
})
</script>