Rosamunda Rosamunda - 2 months ago 6
Javascript Question

Show rows on the fly with JS before submitting the form: nothing gets printed

I'm trying to dynamically show a list of html rows according to the number typed inside and input text of a form.
The form will be submitted and the information saved into a mySQL database using PHP, but I want (before that), to show a list of items on the fly with javascript using another button, and not the submit one.

But it won't work (here's the fiddle).

This is my html form:

<form name="configurarCursoForm" method="POST" action="guardarConfigCurso.php">
<div class="form-group">
<label for="sumarioCurso">Cuántas clases para el Cronograma?</label>
<input type="text" name="cantClases">
<input id='generarCronograma' type='button' onclick='return generarCronograma()' value='Generar Cronograma'>
</div>
<div id="output"></div>


And here's my javascript function:

function generarCronograma() {
var cant = document.forms["configurarCursoForm"]["cantClases"].value;
if (cant && !isNaN(cant)) {
for ($i=0; $i<cant; $i++) {
var e = 0;
var fecha = " Fecha <input style='width:20%;' type='text' name='fecha"+($i+1)+"'> ";
var bolilla = " Bolilla <input style='width:20%;' type='text' name='bolilla"+($i+1)+"'> ";
var docente = " Docente <input style='width:20%;' type='text' name='docente"+($i+1)+"'> ";
var link = " Link <input style='width:20%;' type='text' name='link"+($i+1)+"'> <br>";
$('#output').append(fecha, bolilla, docente, link); //agregamos las celdas necesarias
}
}
}


I'm sure there's some obvious mistake here, but can't find it.

Answer

There are three reasons why the code in the fiddle doesn't work:

  1. The JS has the default fiddle option of being wrapped in an onload handler, which means your function isn't global and can't be accessed from an inline onclick= attribute. Click the JavaScript options button in the top right of the JS window and change the "Load type" option from "onLoad" to "No wrap - in head".

  2. You are trying to use a jQuery function but haven't included jQuery in the fiddle. In the JS options select your preferred version of jQuery.

  3. Your input element has id='generarCronograma', which is the same name as the function. Element IDs are also accessible as global variables, and so using the same name confuses things. You would see this as an error in your browser's console, "Uncaught TypeError: generarCronograma is not a function". Change the id (or remove it, since you don't seem to be using it).

With those three changes it works: https://jsfiddle.net/Lb1prL4k/4/

Comments