VAAA VAAA - 1 year ago 46
jQuery Question

jQuery - How to convert div content into serialized data

I have a div and a button:

<div id="screenlist"></div>
<a href="" id="btnscreen">Add new</a>


Now my
jQuery
code appends to my div some sample data like this:

$('#btnscreen').click(function(e){
e.preventDefault();
$('#screenlist')
.append('www.sampleurl.com</br>');
});


So at the end my div could look like this:

<div id="screenlist">
www.sampleurl.com</br>
www.sampleurl.com</br>
www.sampleurl.com</br>
www.sampleurl.com</br>
www.sampleurl.com</br>
www.sampleurl.com</br>
</div>


I would like to serielize the div's content so I can post that to server and get each element.


Any clue?

Answer Source

If you simply just want to serialize the current html in your screenlist, you can do it like,

$(function() {
  var contents = $('#screenlist').html().split(/\n|\<br>/).filter(function(v) {
    return /\w+/.test(v);
  });
  var data = {};

  for (var k in contents) {
    data[k] = contents[k];
  }

  console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="screenlist">
  www.sampleurl.com</br>
  www.sampleurl.com</br>
  www.sampleurl.com</br>
  www.sampleurl.com</br>
  www.sampleurl.com</br>
  www.sampleurl.com</br>
</div>

Edit: (for your comments)

It's a bad idea to parse html tags with regex, therefore I suggest an alternative approach.

$(function() {
  var data = {};

  $('#screenlist > div').each(function(i, elem) {
    var $elem = $(elem);
    data[$elem.attr('id')] = $elem.text();
  });

  console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="screenlist">
  <div id=1>www.sampleurl.com</div>
  </br>
  <div id=2>www.sampleurl.com</div>
  </br>
  <div id=3>www.sampleurl.com</div>
  </br>
  <div id=4>www.sampleurl.com</div>
  </br>
  <div id=5>www.sampleurl.com</div>
  </br>
</div>