I´m having problems using the Jquery .datepicker plugin in a textbox, when generated using dynamic content (javascript), inside a php page.
Below is my current code. Please help me out finding how to enable Jquery Datepicker on it?
** All I need is an explanation on how shoud I alter the code in "i > 0 && j == 3" textbox creation part.
Thank You in Advance. (I know my code is terrible, I´m a rookie on it!)
<script type="text/javascript">
//Script para gerar os campos para preenchimentos parcelados
function gerarparcelas() {
// desabilitar botão Gerar parcelas ao rodar este script:
document.getElementById("gera_parcelas").disabled = true;
var descr_lancamento_02 = document.getElementById('descr_lancamento_02').value; //Pegar valor do campo descrição do lançamento
var valor_lancamento_02 = document.getElementById('valor_lancamento_02').value; //Pegar valor do campo valor do lançamento (total)
var data_vencimento_02 = document.getElementById('data_vencimento_02').value; //Pegar valor do campo data de vencimento (da 1 parcela)
var qtde_parcelas = document.getElementById('qtde_parcelas').value; //Pegar valor do campo quantidade de parcelas
//converter o número em REAIS digitado no campo em número americano para o sistema calcular:
valor_lancamento_02 = valor_lancamento_02.replace(/\./g,"");
valor_lancamento_02 = valor_lancamento_02.replace(",",".");
// vamos criar o elemento HTML table
var tabela = document.createElement("table");
tabela.width = "750px";
tabela.id = "table_parcela"
tabela.height = "250px";
tabela.border = "1px";
tabela.cellSpacing = "0px";
tabela.cellPadding = "2px";
// vamos criar o corpo da tabela, ou seja, o tbody
var corpo = document.createElement("tbody");
tabela.appendChild(corpo);
var linhas = qtde_parcelas;
linhas++;
// vamos criar quatro linhas contendo quatro células cada uma
for(var i = 0; i < linhas; i++){
var linha = corpo.insertRow(-1);
for(var j = 0; j < 4; j++){
var celula = linha.insertCell(-1);
if (i == 0 && j == 0) {
celula.innerHTML = "<td class='corpo_padrao align='center' valign='middle' bgcolor='#D3D3D3'><strong></p>";
} else if (i == 0 && j == 1) {
celula.innerHTML = "<p class='corpo_padrao align='center' valign='middle' bgcolor='#D3D3D3'><strong>Descrição do lançamento</strong></p>";
} else if (i == 0 && j == 2) {
celula.innerHTML = "<p class='corpo_padrao align='center' valign='middle' bgcolor='#D3D3D3'><strong>Valor R$</strong></p>";
} else if (i == 0 && j == 3) {
celula.innerHTML = "<p class='corpo_padrao align='center' valign='middle' bgcolor='#D3D3D3'><strong>Vencimento</strong></p>";
}
if (i > 0 && j == 0) {
id = i;
celula.innerHTML = id;
}
if (i > 0 && j == 1) {
celula.innerHTML = descr_lancamento_02;
celula.innerHTML="<input type='text' value='" +celula.innerHTML + " - " + id + "/" + qtde_parcelas + "' id='parcelamento_" + i +"_"+ j +"' size='55'>";
}
if (i > 0 && j == 2) {
celula.innerHTML = valor_lancamento_02;
var parcela = celula.innerHTML / qtde_parcelas;
// Reconvertendo o número de U$ para R$
var int = parseInt(parcela.toFixed(2).toString().replace(/[^\d]+/g, ''));
var tmp = int + '';
tmp = tmp.replace(/([0-9]{2})$/g, ",$1");
if (tmp.length > 6)
tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");
if (tmp.length > 9)
tmp = tmp.replace(/([0-9]{3}).([0-9]{3}),([0-9]{2}$)/g,".$1.$2,$3");
if (tmp.length > 12)
tmp = tmp.replace(/([0-9]{3}).([0-9]{3}).([0-9]{3}),([0-9]{2}$)/g,".$1.$2.$3,$4");
if(tmp.indexOf(".") == 0) tmp = tmp.replace(".","");
if(tmp.indexOf(",") == 0) tmp = tmp.replace(",","0,");
parcela = tmp;
// Fim da reconversão de moeda
celula.innerHTML="<input type='text' value='" + parcela + "' id='parcelamento_" + i +"_"+ j +"'>";
}
if (i > 0 && j == 3) {
// criar campo textbox com jquery para Datepicker:
celula.innerHTML = data_vencimento_02;
var $textbox_id = "parcelamento_" + i + "_" + j;
celula.innerHTML = "<input type='text' value='" + celula.innerHTML + "' id='" + $textbox_id + "'>";
$txtdatabox = celula.innerHTML;
$txtdatabox.datepicker(); //This line should be calling the plugin to have the new created textbox above to use Jquery?
}
}
}
// vamos anexar a tabela recém-criada a um elemento div
var $container = document.getElementById("container");
$container.appendChild(tabela);
$container.datepicker(); //Also tried this line to add Datepicker plugin...
}
</script>
You cannot call date picker on the body tag. You could at the end of all your code do
$(".dtp").each(function() {
$(this).datepicker();
}
if you give your inputs the class="dtp"
Related
I'm new to both Progress and JavaScript. I'm getting elements from a temp-table in Progress using json. I'll show part of my code.
$.post({
url: gWS + "/bass/bass054.p",
data: {
"process": "<?php echo $process; ?>"
},
success: function(data){
var table = document.getElementById("table");
var j = 0;
var dataProc = "";
var qtProc = 0;
var item = "";
var sumQt = 0;
var qt_total = 0;
var idGrp = "";
for (var i = 0; i < data["tt-base"].length; i++) {
var row = table.insertRow(j+2);
if (data["tt-base"][i]["cod_id_bloco_edi"] != idGrp && i>=2) {
if (sumQt == qt_total) {
row.style.background = "green";
} else {
row.style.background = "#ff0000";
}
row.insertCell(0).innerHTML = "<b>QT TOTAL:</b>";
row.insertCell(1).innerHTML = "<b>" + item + "</b>";
row.insertCell(2).innerHTML = "<b>" + sumQt + "</b>";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<b>" + qt_total + "</b>";
sumQt = 0;
j++;
row = table.insertRow(j+2);
}
if (data["tt-base"][i]["cdn_segment_edi"] == 44) {
row.style.background = "#00ff00";
dataProc = data["tt-base"][i]["dsl_dados_entr_edi"].substring(7,9) + "/" + data["tt-base"][i]["dsl_dados_entr_edi"].substring(5,7) + "/20" + data["tt-base"][i]["dsl_dados_entr_edi"].substring(3,5) + "</div>";
qtProc = parseInt(data["tt-base"][i]["dsl_dados_entr_edi"].substring(11,20), 10) + "</div>";
row.insertCell(0).innerHTML = dataProc;
row.insertCell(1).innerHTML = qtProc;
row.insertCell(2).innerHTML = " ";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<div class='p6'> </div>";
j++;
sumQt = parseInt(sumQt,10) + parseInt(qtProc,10);
} else if (data["tt-base"][i]["cdn_segment_edi"] == 446) {
if (data["tt-base"][i]["dsl_dados_entr_edi"].indexOf("PRE") == 10) {
document.getElementById("table").deleteRow(j+1);
j--;
row = table.insertRow(j+2);
row.style.background = "#0099CC";
row.insertCell(0).innerHTML = dataProc;
row.insertCell(1).innerHTML = qtProc;
row.insertCell(2).innerHTML = "PREVIS";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<div class='p6'> </div>";
dataProc = '';
qtProc = 0;
j++;
} else if (data["tt-base"][i]["dsl_dados_entr_edi"].indexOf("FIR") == 10) {
document.getElementById("table").deleteRow(j+1);
j--;
row = table.insertRow(j+2);
row.style.background = "#00ff00";
row.insertCell(0).innerHTML = dataProc;
row.insertCell(1).innerHTML = qtProc;
row.insertCell(2).innerHTML = "FIRM";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<div class='p6'> </div>";
dataProc = '';
qtProc = 0;
j++;
}
}
idGrp = data["tt-base"][i]["cod_id_bloco_edi"];
}
}
}).fail(function() {
alert("Not Possible.");
})
So, instead of deleting the row as I'm doing it now I'd like to replace the previous only the cells with the FIRM and PREVIS. I tried using only row.insertCell(2).innerHTML = "PREVIS"; but it didn't work correctly.
Is there any suggestion as to how can I do it? Sorry if I'm not clear enough as i'm new to all this. Thanks for your time.
I managed to do what I wanted after tweaking for hours, lol.
Instead of using insertRow or insertCell, I just used the following
table.rows[j+2].style.background = "#0099CC";
table.rows[j+2].cells[2].innerHTML = "PREVIS";
This way, I was able to replace the content of what I wanted. I still have to change some other details, but the most difficult part is finally gone. Sorry if I wasted your time, but writing here has helped me to see the code in a different angle. I hope my code can help other people.
I have a problem with keeping sliders in sync.
Sliders preview
If I +1 on one of the four sliders, then the others must be substracted with 1/3.
What is the best way to perform this action?
I tried through Javascript already but can't come up with a working code. The selected slider does change value, but the 3 others give weird numbers.
The oninput() method is called when changing one of the sliders. When selecting a sliders and pressing the arrows keys to change the value then nothing happens. When drag and dropping a new value on the slider, also nothing happens. Only when sliding very rapidly.
When clicking on a new value on the slider, it does work somehow..
What am I doing wrong here?
this is the whole function, some variables are written in Dutch...
Code preview:
function showValueSub(sliderValue, parent, aantalKinderen, totaalbedragCategorie, echteParentId, teller, aantalSiblings, opgeroepenDoorHoofdCategorie) {
/*
het labeltje onder de afbeelding van de hoofdcategorie moet niet meer worden aangepast.
document.getElementById("subcat" + range).innerHTML = newValue + " Euro";
##
Parameters:
parent=het begrotingsId van het huidig element.
echteParentId= het begrotingsId van de parent
##
*/
//alert('test');
//###################################################################################################################################################
//#LOOPEN OVER DE SIBLINGS
//enkel loopen over siblings als deze functie wordt uitgevoerd door huidig element, en niet de parent.
//eerst het outputelement onder de slider aanpassen
var siblingElement = document.getElementById(echteParentId + "input" + teller);
if (siblingElement != null) var siblingSlider = parseInt(siblingElement.getAttribute("onchangeviaparent"));
if (siblingElement != null && siblingSlider != 1) {
//als het niet is opgeroepen door een hoofdcategorie: dan output en input aanpasen van huidig element
var huidigOutputElement = document.getElementById(echteParentId + "output" + teller);
huidigOutputElement.innerText = sliderValue;
var aantalAanpasbareSiblings = 0;
var teVerdelenBedragSiblings = 0;
for (var i = 0; i < aantalSiblings - 1; i++) {
var siblingElement = document.getElementById(echteParentId + "." + i);
//tellen hoeveel kindelementen er zijn die aanpasbaar zijn.
if (siblingElement.getAttribute("categoriestatus") != "NIET_AANPASBAAR")
aantalAanpasbareSiblings++;
}
if (aantalAanpasbareSiblings == 0) aantalAanpasbareSiblings = 1;
if (vorigeSliderValueSibling != null)
teVerdelenBedragSiblings = (sliderValue - vorigeSliderValueSibling) / aantalAanpasbareSiblings; //te verdelen bedrag per aanpasbaar siblingElement
else
teVerdelenBedragSiblings = Math.round(sliderValue / aantalAanpasbareSiblings).toFixed(2); //te verdelen bedrag per aanpasbaar siblingElement
for (var i = 0; i < aantalSiblings; i++) {
//het huidig subelement mag niet aangepast worden, checken met een if.
var siblingElement = document.getElementById(echteParentId + "." + i);
if (siblingElement != document.getElementById(echteParentId + "." + teller)) {
if (siblingElement.getAttribute("categoriestatus") != "NIET_AANPASBAAR") {
//in het p element staat een bedrag + de string "EURO".
//eigen p element ophalen
var siblingElementMetBedrag = document.getElementById(echteParentId + "." + i + "p");
var bedrag = parseFloat(siblingElementMetBedrag.innerHTML.substring(0, siblingElementMetBedrag.innerHTML.length - 5).trim());
bedrag -= teVerdelenBedragSiblings; //aftrekken ipv optellen
siblingElementMetBedrag.innerHTML = Math.round(bedrag).toFixed(2) + " Euro";
//siblinginput(slider) element ophalen en proberen aan te passen
var siblingSliderElement = document.getElementById(echteParentId + "input" + i);
if (siblingSliderElement != null) siblingSliderElement.value = Math.round(siblingSliderElement.value - teVerdelenBedragSiblings).toFixed(2);
//output van sibling aanpassen
var siblingSliderOutput =document.getElementById(echteParentId + "output" + i);
if (siblingSliderOutput != null)
siblingSliderOutput.value = Math.round(siblingSliderOutput.value - teVerdelenBedragSiblings).toFixed(2);
}
}
}
}
vorigeSliderValueSibling = sliderValue;
//###################################################################################################################################################
//#LOPEN OVER DE KINDEREN.
var aantalAanpasbareKinderen = 0;
for (var i = 0; i < aantalKinderen; i++) {
var kindElement = document.getElementById(parent + "." + i);
//tellen hoeveel kindelementen er zijn die aanpasbaar zijn.
if (kindElement.getAttribute("categoriestatus") != "NIET_AANPASBAAR")
aantalAanpasbareKinderen++;
}
//als er geen aanpasbarekinderen gevonden zijn, deze standaard op 1 zetten want
//delen door 0 gaat niet.
if (aantalAanpasbareKinderen == 0) aantalAanpasbareKinderen = 1;
//checken of de slider al een keer is aangepast, zo ja huidig bedrag van de slider verminderen met vorige waarde van de slider
if (vorigeSliderValueSub != null)
teVerdelenBedrag = (sliderValue - vorigeSliderValueSub) / aantalAanpasbareKinderen; //te verdelen bedrag per aanpasbaar kindElement
else
teVerdelenBedrag = Math.round(sliderValue / aantalAanpasbareKinderen).toFixed(2); //te verdelen bedrag per aanpasbaar kindElement
for (var i = 0; i < aantalKinderen; i++) {
var kindElement = document.getElementById(parent + "." + i);
if (kindElement.getAttribute("categoriestatus") != "NIET_AANPASBAAR") {
//in het p element staat een bedrag + de string "EURO".
//eigen p element ophalen
var kindElementMetBedrag = document.getElementById(parent + "." + i + "p");
var bedrag = parseFloat(kindElementMetBedrag.innerHTML.substring(0, kindElementMetBedrag.innerHTML.length - 5).trim());
bedrag += teVerdelenBedrag;
kindElementMetBedrag.innerHTML = bedrag + " Euro";
//kindinput element ophalen en proberen aan te passen
var kindSliderElement = document.getElementById(parent + "input" + i);
if (kindSliderElement != null) kindSliderElement.value = sliderValue / aantalAanpasbareKinderen;
}
}
//###################################################################################################################################################
vorigeSliderValueSub = sliderValue;
//alert(siblingSlider.innerHTML);
if (siblingSlider != null) {
$("#" + echteParentId + "input" + teller).attr('onchangeviaparent', '0');
//siblingSlider.onchangeviaparent = '0';
//alert(parseInt(siblingSlider.getAttribute("onchangeviaparent")));
}
//document.getElementById(echteParentId + "." + teller).setAttribute("onchangeViaParent", "0");
//alert(document.getElementById(echteParentId + "input" + teller).getAttribute("onchangeViaParent"));
}
I'm trying to send a list of parameters from JS to an asp.net file, but the file is not receiving the parameters correctly. Sometimes I get the message "Undefined".
Here's my code:
JavaScript
<script type="text/javascript">
$(document).on("click", "[id*=lnkView]", function () {
$("#nome").html($(this).closest("tr").find("td.sDisplayName").text());
$("#Product").html($(this).closest("tr").find(".Produto").text());
$("#IP").html($(this).closest("tr").find("td.sNetworkAddress").text());
$("#DC").html($(this).closest("tr").find("td.dc").text());
$("#comentario").html($(this).closest("tr").find("td.sComment").text());
$("#inicio").html($(this).closest("tr").find("td.inicio").text());
$("#mensagem").html($(this).closest("tr").find(".mensagem").text());
$("#monitor").html($(this).closest("tr").find("td.sMonitorTypeName").text());
$("#dialog").dialog({
width: 1000,
title: "Detalhes para TP",
buttons: {
var width = 150;
var height = 250;
var left = 99;
var top = 99;
var janeleira = window.open("outlookPrimeiro.aspx?" + FIRST VALUE FROM THE FUNCTION ABOVE , 'janela', 'width=' + width + ', height=' + height + ', top=' + top + ', left=' + left + ', scrollbars=yes, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no, setTimeout=1000');
//window.open("outlookPrimeiro.aspx");
//janeleira.onload = function () { janeleira.setTimeout('janeleira.close()', 1000); }
//setTimeout(function () { janeleira(); }, 1);
},
ok: function () {
$(this).dialog('close');
}
},
modal: true
});
return false;
});
function blinker() {
$('.blink').fadeOut(500);
$('.blink').fadeIn(500);
}
setInterval(blinker, 1000); //Runs every second
ASP.NET
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//NECESSÁRIO PARA USAR MARSHALL
using System.Runtime.InteropServices;
//NECESSARIO PARA USAR O OUTLOOK
using aqueleLance = Microsoft.Office.Interop.Outlook;
using OutlookApp = Microsoft.Office.Interop.Outlook.Application;
using testeUsingPrimeiro = Microsoft.Office.Interop.Outlook._AutoFormatRule;
using testeUsingSegundo = Microsoft.Office.Interop.Outlook._AutoFormatRules;
using testeUsingTerceiro = Microsoft.Office.Interop.Outlook.AutoFormatRule;
using testeUsingQuarto = Microsoft.Office.Interop.Outlook.AutoFormatRules;
public partial class outlookPrimeiro : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String nomeDevice = null;
if (Request.QueryString != null)
{
// Seta banco dados
nomeDevice = Request.QueryString.ToString();
}
//DEFINICICOES DE DADOS DO E-MAIL A SER ENVIADO
String paraEmail = "para#email.com.br";
String copiaEmail = "mateus.pereira#linx.com.br";
//String copiaOculta = "";
String assuntoEmail = "Using Outlook 2013";
String corpo = "<html><body><div style='width:95%;text-align: center;background-color: black'><table style='width: 100%;text-align: center'><tr style='background-color:#5B2E90'><td style='color: white'>Prioridade</td><td style='color: white'>Acionamento</td><td style='color: white'>KBN</td><td style='color: white'>Device</td><td style='color: white'>IP</td><td style='color: white'>DC</td><td style='color: white'>WUG</td><td style='color: white'>Diretorio</td><td style='color: white'>Monitor</td><td style='color: white'>Comentario</td><td style='color: white'>Tempo Down</td><td style='color: white'>Inicio</td><td style='color: white'>TP</td></tr><tr><td style='color: orange'>Prioridade</td><td style='color: orange'>Acionamento</td><td style='color: orange'>KBN</td><td style='color: orange'>"+ nomeDevice + "</td><td style='color: orange'>IP</td><td style='color: orange'>DC</td><td style='color: orange'>WUG</td><td style='color: orange'>Diretorio</td><td style='color: orange'>Monitor</td><td style='color: orange'>Comentario</td><td style='color: orange'>Tempo Down</td><td style='color: orange'>Inicio</td><td style='color: orange'>TP</td></tr></table></div></body></html>";
//banco(?)
//string host = "127.0.0.1\SQLEXPRESSNOC";
//string usuario = "NOME DO USUÁRIO";
//string senha = "SENHA DO USUARIO";
//string banco = "NOME DO USUARIO";
//CRIA NOVO APP USANDO Microsoft.Office.Interop.Outlook.Application
OutlookApp appDoOutlook = new OutlookApp();
//CRIA E-MAIL
aqueleLance.MailItem itemDoMail = appDoOutlook.CreateItem(aqueleLance.OlItemType.olMailItem) as aqueleLance.MailItem;
//QUAL CONTA VAI ENVIAR? NECESSÁRIO TER A CONTA NA MÁQUINA
string nomeDaConta = "para#email.com.br";
//CRIA SESSÃO
aqueleLance.NameSpace sessao = itemDoMail.Session;
//PEGA CONTAS PRESENTES NA MÁQUINA
aqueleLance.Accounts contaAccounts = sessao.Accounts;
//FOR 1 ATÉ FINAL DO NÚMERO DE CONTAS
for (int i = 1; i <= contaAccounts.Count; i++)
{
//aqueleLance.Account contaAccount RECEBE O VALOR DO FOR
aqueleLance.Account contaAccount = contaAccounts[i];
//SE A CONTA EXISTE, ELE VAI ENVIAR
//(COMPARAÇÃO FEITA EM LOWER CASE
if (contaAccount.DisplayName.ToLower() == nomeDaConta.ToLower())
{
//COMANDO PARA ENVIAR USANDO A CONTA XXXXX
itemDoMail.SendUsingAccount = contaAccount;
//LIBERA VARIAVEL
Marshal.ReleaseComObject(contaAccount);
//PARA O COMANDO
break;
}
}
//PARA QUEM ENVIA O E-MAIL
itemDoMail.To = paraEmail;
//ENVIAR COM COPIA PARA
itemDoMail.CC = copiaEmail;
//COPIA OCULTA
//itemDoMail.BCC = copiaOculta;
//ASSUNTO DO EMAIL
itemDoMail.Subject = assuntoEmail;
//CORPO DO EMAIL EM HTML
itemDoMail.HTMLBody = corpo;
//"<html><body>Enviado pelo <strong>Outlook</strong> 2013<br/> Teste do envio com CC e BCC.<br/><br/></body></html>"
//IMPORTANCIA DO EMAIL
itemDoMail.Importance = aqueleLance.OlImportance.olImportanceHigh;
//ENVIA O EMAIL
//NÃO É POSSÍVEL VER ANTES DE ENVIAR SEM HABILITAR O DISPLAY ABAIXO
//itemDoMail.Send();
//HABILITE ISSO PARA VER A MENSAGEM ANTES DE ENVIAR
//PRECISA TIRAR O SEND ACIMA
itemDoMail.Display(false);
//LIBERA CONTAS
Marshal.ReleaseComObject(contaAccounts);
//LIBERA SESSÃO
Marshal.ReleaseComObject(sessao);
}
}
The variables you are posting should be assigned to a parameter. Your querystring doesn't seem to start with a variablename.
Request.QueryString is a collection of variables that you can post.
Request the page like this:
window.open("outlookPrimeiro.aspx?variablename=" + value);
Consecutive variables should be added with the & sign:
window.open("outlookPrimeiro.aspx?variablename=" + value + "&variablename2= " + value2);
On the serverside you can read the variable like this:
string variable = Request.QueryString["variablename"]
Good afternoon, I am developing a small script that analyzes the DOM of an HTML page and write on screen the tree of nodes.
It is a simple function that is called recursively for get all nodes and their children. The information for each node is stored in an array (custom object).
I have gotten get all the nodes in the DOM, but not how to paint in a tree through nested lists.
JSFIDLE
https://jsfiddle.net/06krpdyh/
HTML
<html>
<head>
<title>Formulario para validar</title>
<script type="text/javascript" src="actividad_1.js">Texto script</script>
</head>
<body>
<p>Primer texto que se visualiza en la Pagina</p>
<div>Esto es un div</div>
<div>Otro div que me encuentro</div>
<p>Hay muchos parrafos</p>
<ul>
<li>Lista 1</li>
<li>Lista 2</li>
<li>Lista 3</li>
</ul>
<button type="button" id="muestra_abol">Muestra Arbol DOM</button>
</body>
</html>
JS
// Ejecuta el script una vez se ha cargado toda la página, para evitar que el BODY sea NULL.
window.onload = function(){
// Evento de teclado al hacer click sobre el boton que muestra el arbol.
document.getElementById("muestra_abol").addEventListener("click", function(){
muestraArbol();
});
// Declara el array que contendrá los objetos con la información de los nodos.
var nodeTree = [];
// Recoge el nodo raíz del DOM.
var obj_html = document.documentElement;
// Llama a la función que genera el árbol de nodos de la página.
getNodeTree(obj_html);
console.log(nodeTree);
// Función que recorre la página descubriendo todo el árbol de nodos.
function getNodeTree(node)
{
// Comprueba si el nodo tiene hijos.
if (node.hasChildNodes())
{
// Recupera la información del nodo.
var treeSize = nodeInfo(node);
// Calcula el índice del nodo actual.
var treeIndex = treeSize - 1;
// Recorre los hijos del nodo.
for (var j = 0; j < node.childNodes.length; j++)
{
// Comprueba, de forma recursiva, los hijos del nodo.
getNodeTree(node.childNodes[j]);
}
}
else
{
return false;
}
}
// Función que devuelve la información de un nodo.
function nodeInfo(node,)
{
// Declara la variable que contendrá la información.
var data = {
node: node.nodeName,
parent: node.parentNode.nodeName,
childs: [],
content: (typeof node.text === 'undefined'? "" : node.text)
}
var i = nodeTree.push(data);
return i;
}
// Función que devuelve los datos de los elementos hijos de un nodo.
function muestraArbol()
{
var txt = "";
// Comprueba si existen nodos.
if (nodeTree.length > 0)
{
// Recorre los nodos.
for (var i = 0; i < nodeTree.length; i++)
{
txt += "<ul><li>Nodo: " + nodeTree[i].node + "</li>";
txt += "<li> Padre: " + nodeTree[i].parent + "</li>";
txt += "<li>Contenido: " + nodeTree[i].content + "</li>";
txt += "</ul>";
}
document.write(txt);
}
else
{
document.write("<h1>No existen nodos en el DOM.</h1>");
}
}
};
Does anyone comes up how to draw a nested tree to glance at the parent and child nodes you distinguish?
Greetings and thank you
You have a recursive DOM reader, but you also need a recursive outputter. You're also dealing with a one dimensional array when you need a multi-level object (tree).
We'll start with refactoring getNodeTree. Instead of adding to a global array (nodeTree in your code), let's have it return a tree:
function getNodeTree (node) {
if (node.hasChildNodes()) {
var children = [];
for (var j = 0; j < node.childNodes.length; j++) {
children.push(getNodeTree(node.childNodes[j]));
}
return {
nodeName: node.nodeName,
parentName: node.parentNode.nodeName,
children: children,
content: node.innerText || "",
};
}
return false;
}
Same for muestraArbol (for our monolingual friends out there, it means "show tree"): We'll have it work recursively and return a string containing nested lists:
function muestraArbol (node) {
if (!node) return "";
var txt = "";
if (node.children.length > 0) {
txt += "<ul><li>Nodo: " + node.nodeName + "</li>";
txt += "<li> Padre: " + node.parentName + "</li>";
txt += "<li>Contenido: " + node.content + "</li>";
for (var i = 0; i < node.children.length; i++)
if (node.children[i])
txt += "<li> Hijos: " + muestraArbol(node.children[i]) + "</li>";
txt += "</ul>";
}
return txt;
}
Finally, if we put it together in a snippet:
var nodeTree = getNodeTree(document.documentElement);
console.log(nodeTree);
function getNodeTree(node) {
if (node.hasChildNodes()) {
var children = [];
for (var j = 0; j < node.childNodes.length; j++) {
children.push(getNodeTree(node.childNodes[j]));
}
return {
nodeName: node.nodeName,
parentName: node.parentNode.nodeName,
children: children,
content: node.innerText || "",
};
}
return false;
}
function muestraArbol(node) {
if (!node) return "";
var txt = "";
if (node.children.length > 0) {
txt += "<ul><li>Nodo: " + node.nodeName + "</li>";
txt += "<li> Padre: " + node.parentName + "</li>";
txt += "<li>Contenido: " + node.content + "</li>";
for (var i = 0; i < node.children.length; i++)
if (node.children[i])
txt += "<li> Hijos: " + muestraArbol(node.children[i]) + "</li>";
txt += "</ul>";
}
return txt;
}
document.getElementById("muestra_abol").addEventListener("click", function() {
document.getElementById("result").innerHTML = muestraArbol(nodeTree);
});
<title>Formulario para validar</title>
<body>
<p>Primer texto que se visualiza en la Pagina</p>
<div>Esto es un div</div>
<div>Otro div que me encuentro</div>
<p>Hay muchos parrafos</p>
<ul>
<li>Lista 1</li>
<li>Lista 2</li>
<li>Lista 3</li>
</ul>
<button type="button" id="muestra_abol">Muestra Arbol DOM</button>
<div id="result"></div>
</body>
Finally: My apologies, for my Spanish-JavaScript reading skills are not in their prime. :)
$.ajax({
url : SrvHandlerCalendar,
type : 'post',
data : {"persona": str, "day2" : dia + '.' + mes + '.' + anio},
timeout : 2000,
tryCount : 0,
retryLimit : 3,
cache: false,
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
var xml;
if (typeof data == 'string') {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
$(xml).find('evento').each(function(){
ai++;
var id = $(this).attr('id');
var rdia = $(this).find('dia').text();
var rmes = $(this).find('mes').text();
var ranio = $(this).find('anio').text();
var hora = $(this).find('hora').text();
var horario = $(this).find('horario').text();
var desc = $(this).find('d').text();
var estado = $(this).find('estado').text();
var localidad = $(this).find('localidad').text();
var colonia = $(this).find('colonia').text();
var calle = $(this).find('calle').text();
var numero = $(this).find('ncasa').text();
var telefono = $(this).find('telefono').text();
var celular = $(this).find('celular').text();
var persona = $(this).find('persona').text();
var creador = $(this).find('creador').text();
var observaciones = $(this).find('observaciones').text();
if(persona != $("#personas_select option:selected").text()) return 1;
var html = "<font size=5>Informacion del evento con <u>" + persona + "</u></font><br>";
html += "<font size=2>"+desc+"</font><br><br><br>";
html += "<table class=\"datatable\" cellpadding=10>"
html += "<tr><td><strong>Hora de la Cita</strong></td><td>" + hora + horario+"</td></tr>";
html += "<tr><td><strong>Domicilio</strong></td><td>" + calle + " #"+numero+"</td></tr>";
html += "<tr><td><strong>Colonia</strong></td><td>" +colonia+"</td></tr>";
//html += "<tr colspan=\"2\" style=\"text-align: center;\"><td>Datos de contacto</td></tr>";
html += "<tr><td><strong>Telefono</strong></td><td>" + telefono +"</td></tr>";
html += "<tr><td><strong>Celular</strong></td><td>" + celular +"</td></tr>";
html += "<tr><td><strong>Encuestador</strong></td><td>" + creador +"</td></tr>"
html += "<tr><td><strong>Observaciones</strong></td><td>" + observaciones +"</td></tr></table>";
$('#datos').html(html);
/*
var html = "<font size=5>Informacion del evento con <u>" + persona + "</u></font><br>";
html += "<font size=2>"+desc+"</font><br>";
html += "<table>"
html += " <tr> <td>Hora de la Cita</td><td>horario y fecha</td></tr>";
html += "<tr> <td>Domicilio</td><td>vdomicilio</td></tr>";
html += "<tr><td>Colonia</td><td>vcolonia</td></tr>";
html += "<tr><td>Datos de contacto</td><td>(no hay otra columna)</td></tr>";
html += "<tr><td>telefono</td><td></td></tr>";
html += "<tr><td>celular</td><td></td></tr>";
html += "<tr><td>encuestador</td><td></td></tr></table>";
*/
});
if($("#datos").html() == loading){
$('#datos').html("Uups! No hay datos de evento para esta persona. <strong>Notificar de inmediato al administrador del sistema</strong> <a href=\"#\" onclick='alert(\"No se encontro el primer atributo XML\" + \" "+" \" )'> Ficha Técnica</a>");
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
$('#datos').html(loading);
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
$('#datos').html("Uups! Hubo un error procesando su solicitud <a href=\"#\" onclick='alert(\"Respuesta HTTP: \" + \" "+ xhr.status+" \" + \"\\nManejador del servidor: \" + \" " + SrvHandlerCalendar + " \" + \"\\nDescripcion de error: \" + \" " + textStatus + " \" + \"\\nIntentos: \" + \" " + this.retryLimit + " \" )'> Ficha Técnica</a>");
return;
}
if (xhr.status == 500) {
$('#datos').html('Uups! Hubo un error con el servidor. Intente nuevamente mas tarde y pongase en contacto con el administrador de sistemas.');
} else {
$('#datos').html("Uups! Hubo un error procesando su solicitud <a href=\"#\" onclick='alert(\"Respuesta HTTP: \" + \" "+ xhr.status+" \" + \"\\nManejador del servidor: \" + \" " + SrvHandlerCalendar + " \" + \"\\nDescripcion de error: \" + \" " + textStatus + " \" )'> Ficha Técnica</a>");
}
}
});`
And basically this:
var xml;
if (typeof data == 'string') {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
$(xml).find('evento').each(function(){
ai++;
var id = $(this).attr('id');
var rdia = $(this).find('dia').text();
var rmes = $(this).find('mes').text();
var ranio = $(this).find('anio').text();
var hora = $(this).find('hora').text();
var horario = $(this).find('horario').text();
var desc = $(this).find('d').text();
var estado = $(this).find('estado').text();
var localidad = $(this).find('localidad').text();
var colonia = $(this).find('colonia').text();
var calle = $(this).find('calle').text();
var numero = $(this).find('ncasa').text();
var telefono = $(this).find('telefono').text();
var celular = $(this).find('celular').text();
var persona = $(this).find('persona').text();
var creador = $(this).find('creador').text();
var observaciones = $(this).find('observaciones').text();
if(persona != $("#personas_select option:selected").text()) return 1;
var html = "<font size=5>Informacion del evento con <u>" + persona + "</u></font><br>";
html += "<font size=2>"+desc+"</font><br><br><br>";
html += "<table class=\"datatable\" cellpadding=10>"
html += "<tr><td><strong>Hora de la Cita</strong></td><td>" + hora + horario+"</td></tr>";
html += "<tr><td><strong>Domicilio</strong></td><td>" + calle + " #"+numero+"</td></tr>";
html += "<tr><td><strong>Colonia</strong></td><td>" +colonia+"</td></tr>";
//html += "<tr colspan=\"2\" style=\"text-align: center;\"><td>Datos de contacto</td></tr>";
html += "<tr><td><strong>Telefono</strong></td><td>" + telefono +"</td></tr>";
html += "<tr><td><strong>Celular</strong></td><td>" + celular +"</td></tr>";
html += "<tr><td><strong>Encuestador</strong></td><td>" + creador +"</td></tr>"
html += "<tr><td><strong>Observaciones</strong></td><td>" + observaciones +"</td></tr></table>";
$('#datos').html(html);
/*
var html = "<font size=5>Informacion del evento con <u>" + persona + "</u></font><br>";
html += "<font size=2>"+desc+"</font><br>";
html += "<table>"
html += " <tr> <td>Hora de la Cita</td><td>horario y fecha</td></tr>";
html += "<tr> <td>Domicilio</td><td>vdomicilio</td></tr>";
html += "<tr><td>Colonia</td><td>vcolonia</td></tr>";
html += "<tr><td>Datos de contacto</td><td>(no hay otra columna)</td></tr>";
html += "<tr><td>telefono</td><td></td></tr>";
html += "<tr><td>celular</td><td></td></tr>";
html += "<tr><td>encuestador</td><td></td></tr></table>";
*/
});
if($("#datos").html() == loading){
$('#datos').html("Uups! No hay datos de evento para esta persona. <strong>Notificar de inmediato al administrador del sistema</strong> <a href=\"#\" onclick='alert(\"No se encontro el primer atributo XML\" + \" "+" \" )'> Ficha Técnica</a>");
}
Only works on Chrome/Firefox and Not on IE.
I don't know why, I googled about JQuery and IE errors, tried the 'fixes' and they still do not work.
Thank you in advance.
UPDATE
It now works.
The problem with IE is that the XML It was receiving was bad because IE doesn't allow áéíóú letters (commonly used in spanish) instead displaying a square character therfor it could't process the XML.