-1

Well I have data retrieved from ajax, I need to parse it in order to generate inputs with different <input> values. While clicking on <a> that should get near standing input value and go to ajax

<script type="text/javascript">
function proceed() {
  var ID = document.getElementById('btnid').value;//probably that`s the wort way, because all of `<a>` buttons would have same id
  //ajax with ID to proceed further
}
$.ajax({
  async: false,
  type: "POST",
  url: "../api/",
  data: {'data': "mydata"},
  dataType: 'JSON',
  complete: function (res) {
    for(var i = 0; i < 10; i++) {
    document.getElementById('nie').innerHTML = "
      <ul class=\"somec\">
      <li class=\"liclass\">
      </input id=\"btnid\" value=\""+res.response[i].animal+"\" class=\"thatclass\" onclick=\"proceed();\"></input>//different values
      <a id="clicker" onclick="proceed()"></a>//clickable link
      </li>
      </ul>
    ";
    }
  });
</script>
<html>
<div id="nie">
</div>
</html>

Any help or advises for solution ?

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Khuma
  • 57
  • 8

1 Answers1

0

You cannot have more than one id in a single DOM -- only one unique id is allowed. Since jQuery is used here, you can take advantages of the other methods and API it provides.

First of all, I would move the loop to success handler of $.ajax because that ensures that I have data returned from the server.

As for "appending" input and anchor pairs, use $.append. What you're currently doing is just updating #nie with the last element's data in the loop.

For events, delegate the clicks on anchors. This is better because you might continue adding more elements, so you have to go through binding them to an event.

And please, don't set async to false in $.ajax settings. This has unexpected results and makes the browser slow to point that freezes and crashes. jQuery ajax async: false causes a strange warning?

$(function(){

  var $nie = $('#nie');

  // Delegate the click event
  $(document).on('click', '.clicker' function(){

    var id = $(this).siblings('input').val();
    // Use id in upcoming AJAX request.
  });

  $.ajax({
    type: "POST",
    url: "../api/",
    data: {'data': "mydata"},
    dataType: 'JSON',
    success: function (res){

      $.each(res.response, function(i, r){

        $nie.appeand('<ul class="somec">\
        <li class="liclass">\
        <input value="'+ r.animal+ '" class="thatclass"/>\
        <a class="clicker"></a>\
        </li>\
        </ul>');
      });
    }
  });
});
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Adam Azad
  • 11,171
  • 5
  • 29
  • 70