AjayK AjayK - 7 months ago 11
Javascript Question

how to make json string of the chechbox checked div text

how to make json string with jquery on button click but text should be whose chechbox checked.

These are Dynamically Created div

<div class="div1">
<input type="checkbox" class="checkbox" value="1">
<div class="divdata">divtext1</div>
<span class="spandata">spantext1</span>
</div>
<div class="div1">
<input type="checkbox" class="checkbox" value="1">
<div class="divdata">divtext2</div>
<span class="spandata">spantext2</span>
</div>
<div class="div1">
<input type="checkbox" class="checkbox" value="1">
<div class="divdata">divtext3</div>
<span class="spandata">spantext3</span>
</div>
<input type="submit" id="btndisplay" value="Display Data">




This is Desire output want in a textarea

<textarea>
{
"mydata":[
{"divdata":"divtext1", "spandata":"spantext1"},
{"divdata":"divtext2", "spandata":"spantext2"},
{"divdata":"divtext3", "spandata":"spantext3"}
]
}
</textarea>




jQuery code

$("#btndisplay").click(function(){
var divdata = $('.div1 input[type=checkbox]:checked').siblings('.divdata').text();
var spandata = $('.div1 input[type=checkbox]:checked').siblings('.spandata').text();
$('textarea').append(....); // here i am not getting understand.
});

Answer

I believe what you are wanting is along these lines.

JS

$('#btndisplay').click(function(){
  var obj = {
    "myData": []
  };

  $('.div1').each(function() {
    if($(this).find('.checkbox').is(':checked')) {

      obj["myData"].push({
        'divdata': $(this).find('.divdata').text(),
        'spandata': $(this).find('.spandata').text()
      });

    }
  });

  $('textarea').val(JSON.stringify(obj));
});

See js fiddle https://jsfiddle.net/23pf5t10/4/

Comments