Bruno Gutierrez Bruno Gutierrez - 5 months ago 12
Javascript Question

Script is not running when added dynamically

{include file="head.tpl" title="Combate"}
{include file="navBar.tpl" dir=$dir}
<table id="CombatLister">

</table>

Nombre: <input type="text" id="nombrePJ">
AC <input type="number" id="ACPJ">
Iniciativa <input type="number" id="Init">
<button id="aƱadirParty" onclick="addPJButt()">AƱadir</button>



<script>

function addPJButt(){
var name=document.getElementById("nombrePJ").value;
var ac=document.getElementById("ACPJ").value;
var iniciativa=parseInt(document.getElementById("Init").value);
addPJ(name,ac,iniciativa);
}
function addPJ(nombre,ac,init){
var table=document.getElementById("CombatLister");
var row=table.insertRow(0);
var cellNombre=row.insertCell(0);
var cellInit=row.insertCell(1);
var cellAc=row.insertCell(2);
cellNombre.innerHTML=nombre;
cellInit.innerHtml=init;
cellAc.innerHtml=ac;
}

</script>
<script>
{$x=0}
{foreach $party as $pj}

addPJ({$pj.nombre},{$pj.ac},{$pj.init})

{/foreach}
</script>


I have a smarty template that using an array from another page, adds it to the "CombatLister" table. however, for some reason, the addPJ() Script does not run. Im just learning the ropes of Javascript, so maybe im skipping something, but so far, i've got no answers on why it does not work.

I tried to check if the addPJ() script was wrong, using the addPJButt(), but the script is working: When i put data on the input types up there, they add the name correctly.

I dont think its a problem of Smarty. checking the source code of the page its similar, writting this where i call $pj:

<script>

addPJ(Galahad,14,5);

</script>


PS: As an extra problem, but not so important, on the insertCell methods of addPJ only the first cell is added.

Answer

addPJ(Galahad,14,5); is looking for an undefined variable Galahad.

you need to quote it so it gets printed as javascript string

Try

addPJ('{$pj.nombre}',{$pj.ac},{$pj.init})

Note: I haven't worked with smarty in years and assume the quotes will be literals