Modify and read span from jquery with the function load

0

I hope you can help me. I have problems when from jquery I intend to read the value of a span after calling the load () function. The span is created dynamically by javascript each span carries an input that is also created dynamically. all the span are in an array and the inputs in another array, this with the purpose of traversing them, The problem is that I can not access the value of the span in the first click on the button, from the second it starts to give me the values. Javascript code

<script type="text/javascript">


$(document).ready(function() {
      var num=0;
    $("#add").click(function() {
      var div = document.createElement("input");
      div.setAttribute('id',num);
      div.setAttribute('placeholder','DOI '+ num);
      div.setAttribute('name','doi2[]');
      div.setAttribute('class','form-control');
      document.getElementById('dinamico').appendChild(div);

      var spnd = document.createElement("span");
      spnd.setAttribute('id',"span"+num);
      spnd.setAttribute('name','spndoi2[]');
      div.setAttribute('class','form-control');
      document.getElementById('dinamico').appendChild(spnd);

      var salto = document.createElement('br');
      document.getElementById('dinamico').appendChild(salto);
      num++;
    });
  });
$(document).ready(function() { 
    $("#verifica").click(function() {
            var doiarray = document.getElementsByName('doi2[]');
            var spndoiarray = document.getElementsByName('spndoi2[]');
            for(var i = 0; i < doiarray.length; i++){
               $('#span'+i).load("pagina.php?valor="+doiarray[i].value, function(){
               console.log($('#span'+i).text());
        });
      }
    });
});
</script>

Page Code.php

<?php
echo $_GET['valor'];
?>   
    
asked by Jesus Regalado 27.03.2017 в 01:18
source

1 answer

0

Because the load function is asynchronous and you can not read the span values with the for cycle index, instead use:

 $(this).text()
    
answered by 27.03.2017 / 02:28
source