undefinedbr / - Javascript - DOM - checkboxs

0

I have a select with four options, I can choose the ones you want, when you press the button "send" you should send the text of the selected options to div .

This is my code:

//Función que crea una caja con los datos del resumen. Se debe crear usando DOM.
function crearCajaResumen() {
  //Creamos el elemento/objeto que deseamos, sea <p> o <div> o <form>, etc.
  var div = document.createElement("div");
  //DIV tiene la propiedad style, la cual permite acceder a atributos CSS. Ejemplo: div.style.width = "280px"; ...
  div.setAttribute("style", "width: 280px; height: 170px; background-color: #FE775A; float: left;");
  //Guardamos en una variable el elemento/objeto que deseamos, <body>
  //var variable = document.getElementsByTagName("etiqueta")[posicion];
  var body = document.getElementsByTagName("body")[0];
  //Añadimos al documento body un hijo llamado "div".
  document.body.appendChild(div);
  //Guardamos en una variable el elemento/objeto que deseamos, <center>
  var center = document.getElementsByTagName("center")[0];
  //Insertamos el elemento "div" antes que el "center".
  body.insertBefore(div, center);
  //Creamos un nodo de texto que agregaremos al div.
  var titulo = document.createTextNode("DATOS RESUMEN FORMULARIO:\n\n");
  //Añade un nuevo nodo al final de la lista.
  div.appendChild(titulo);
  //Creamos un nodo de texto que agregamos al div.
  var contar = document.createTextNode("Has seleccionado " + contar_seleccionados() + " elementos.");
  div.appendChild(contar);
}

var texto_opciones = ["Analisis y programacion", "Hardware, redes y seguridad", "Administracion de bases de datos", "Telecomunicaciones"];
var textos_seleccionados = "";
//Función que cuenta los checkboxs seleccionados (marcados).
function contar_seleccionados() {
  //Guardamos en una variable los checkboxs (un array) del elemento <form> con la propiedad checkbox.
  var checkboxs = document.getElementById("miformulario").getElementsByName("prefe");
  var contador = 0;
  //Recorremos el array y guardamos en una variable los checkboxs seleccionados.
  for (var i = 0; i < checkboxs.length; i++) {
    
    if (checkboxs[i].checked) {
      contador = contador + 1;
      textos_seleccionados = textos_seleccionados + texto_opciones[i] + "<br/>";
    }//Cerramos el for para que me acepte la correcion
  }
  console.log(textos_seleccionados);
  console.log(contador);
  return contador;
}


// **Manejo de eventos "onclick" y métodos enviar.**
miformulario.btnEnviar.addEventListener("click", function() {
  return confirmEnviar();
}, false);

function confirmEnviar() {
  var pregunta = confirm("¿Deseas enviar el formulario?");
  if (pregunta == true) {
    deshabilitar_btnEnviar();
  } else {
    //No hacer nada.
    event.preventDefault();
  }
}

function deshabilitar_btnEnviar() {
  miformulario.btnEnviar.disabled = true;
  miformulario.btnEnviar.value = "Enviando...";
  setTimeout(function() {
    miformulario.btnEnviar.disabled = false;
    miformulario.btnEnviar.value = "Enviar";
    //Llamada a la función crearCajaResumen();
    crearCajaResumen();
  }, 3000);
  return false;
}
<form id="miformulario">
  <table>
    <tr>
      <td align=left colspan=4>&nbsp;&nbsp;&nbsp;<u>Selecciona tus Preferencias:</u></td>
    </tr>
    <tr>
      <td align=right></td>
      <td align=left><input type="checkbox" name="prefe" value="si" colspan=3>Analisis y programacion</td>
    </tr>
    <tr>
      <td align=right></td>
      <td align=left><input type="checkbox" name="prefe" value="si" colspan=3>Hardware, redes y seguridad</td>
    </tr>
    <tr>
      <td align=right></td>
      <td align=left><input type="checkbox" name="prefe" value="si" colspan=3>Administracion de bases de datos</td>
    </tr>
    <tr>
      <td align=right></td>
      <td align=left><input type="checkbox" name="prefe" value="si" colspan=3>Telecomunicaciones</td>
    </tr>
  </table>
  <input type="button" id="btnEnviar" value="Enviar" />
</form>

Why do I select the marked options well but the texts are not displayed?

And this one the error by console:

  

funciones.js: 446 undefined<br/>undefined<br/>undefined<br/>undefined<br/>
  funciones.js: 447 4

    
asked by omaza1990 18.05.2017 в 13:14
source

2 answers

1

The texts you want to rescue, MUST go to the attribute% co_of% of the inputs, as you have them, they have nothing to do with the checkboxes, they all have the value% co_of%. If it's just Javascript you can try:

// **Manejo de eventos "onclick" y métodos enviar.**
miformulario.btnEnviar.addEventListener("click", function() {
  return confirmEnviar();
}, false);

//Función que crea una caja con los datos del resumen. Se debe crear usando DOM.
function crearCajaResumen() {
  //Creamos el elemento/objeto que deseamos, sea <p> o <div> o <form>, etc.
  var div = document.createElement("div");
  //DIV tiene la propiedad style, la cual permite acceder a atributos CSS. Ejemplo: div.style.width = "280px"; ...
  div.setAttribute("style", "width: 280px; height: 170px; background-color: #FE775A; float: left;");
  //Guardamos en una variable el elemento/objeto que deseamos, <body>
  //var variable = document.getElementsByTagName("etiqueta")[posicion];
  var body = document.getElementsByTagName("body")[0];
  //Añadimos al documento body un hijo llamado "div".
  document.body.appendChild(div);
  //Guardamos en una variable el elemento/objeto que deseamos, <center>
  var center = document.getElementsByTagName("center")[0];
  //Insertamos el elemento "div" antes que el "center".
  body.insertBefore(div, center);
  //Creamos un nodo de texto que agregaremos al div.
  var titulo = document.createTextNode("DATOS RESUMEN FORMULARIO:\n\n");
  //Añade un nuevo nodo al final de la lista.
  div.appendChild(titulo);
  //Creamos un nodo de texto que agregamos al div.
  //var contar = document.createTextNode("Has seleccionado " + contar_seleccionados() + " elementos.");
  
  var seleccionados = [];
  var inputElements = document.getElementsByName("prefe");
  for(var i=0; inputElements[i]; ++i){
      if(inputElements[i].checked){
           seleccionados.push(inputElements[i].value);
      }
  }
  var contar = document.createTextNode("Has seleccionado " + seleccionados.length + " elementos.");
  var salto = document.createElement("br")
  div.appendChild(contar);
  div.appendChild(salto);


  seleccionados.forEach(function(value, index, array) {
      var salto = document.createElement("br")
      var val = document.createTextNode(value);
      div.appendChild(salto);
      div.appendChild(val);
  });
}

function deshabilitar_btnEnviar() {
  miformulario.btnEnviar.disabled = true;
  miformulario.btnEnviar.value = "Enviando...";
  setTimeout(function() {
    miformulario.btnEnviar.disabled = false;
    miformulario.btnEnviar.value = "Enviar";
    //Llamada a la función crearCajaResumen();
    crearCajaResumen();
  }, 3000);
  return false;
}

function confirmEnviar() {
  var pregunta = confirm("¿Deseas enviar el formulario?");
  if (pregunta == true) {
    deshabilitar_btnEnviar();
  } else {
    //No hacer nada.
    event.preventDefault();
  }
}
<form id="miformulario">
          <table>
            <tr>
              <td align=left colspan=4>&nbsp;&nbsp;&nbsp;<u>Selecciona tus Preferencias:</u></td>
            </tr>
            <tr>
              <td align=right></td>
              <td align=left><input type="checkbox" name="prefe" value="Analisis y programacion" colspan=3>Analisis y programacion</td>
            </tr>
            <tr>
              <td align=right></td>
              <td align=left><input type="checkbox" name="prefe" value="Hardware, redes y seguridad" colspan=3>Hardware, redes y seguridad</td>
            </tr>
            <tr>
              <td align=right></td>
              <td align=left><input type="checkbox" name="prefe" value="Administracion de bases de datos" colspan=3>Administracion de bases de datos</td>
            </tr>
            <tr>
              <td align=right></td>
              <td align=left><input type="checkbox" name="prefe" value="Telecomunicaciones" colspan=3>Telecomunicaciones</td>
            </tr>
          </table>
          <input type="button" id="btnEnviar" value="Enviar" />
        </form>
    
answered by 18.05.2017 / 16:07
source
0

You should restart the variable as soon as you enter the method, if you are not going to be coupling the new results with the previous ones every time you click on the button. I would miss seeing what you call the methods, I've pasted it on a jsfiddle and it works perfectly for me.

Add the button code and its onClick

EDITING

In line document.getElementById("miformulario").getElementsByTagName("input") you are removing all the inputs of the form, and even if you check that name='prefe' the variable i is increasing, so that when it reaches the checkbox , the variable i reaches a value greater than the size of Array and when you pass you get undefined

The line should be document.getElementById("miformulario").getElementsByName("prefe")

    
answered by 18.05.2017 в 13:29