Lucy Lucy - 7 months ago 12
Javascript Question

loop through div with different elements

I generated elements and put them in MyDiv

$("#MyDiv").append('<input type=text class = "form-control" id=tb' + row.PropertyName + ' ' + 'value="Text' + row.PropertyName + '" />');
$("#MyDiv").append(' <input type="hidden" name="hid" value= "' + row.PropertyId + '">');


Now I need to extract the
row.PropertyName
and
row.PropertyId


I need something like this:

var arrText = new Array();
$('#MyDiv > input[type = text]').each(function () {

var id = $(this).id.val();
var text = $(this).text.val();

var data = {
'id': id,
'text': text
}

Answer

I guess this is what you want.

$(function(){
  var PropertyName = "pn1";
  var PropertyId = "pn2";
$("#MyDiv").append('<input type="text" class = "form-control" id="tb"' + PropertyName + ' ' +
                       'value="Text' + PropertyName + '" />');
 $("#MyDiv").append('  <input type="hidden" name="hid" value= "' + PropertyId + '">');
  
  $('#MyDiv > input[type = "text"]').each(function(){
    
    var id = $(this).val();
    var text = $(this).next('input[type = "hidden"]').val();
    var data = {
      id: id,
      text: text
    }
    alert(data.id + data.text);
  })
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="MyDiv"></div>