Jquery each loop creating a json output

I have bin working on this for hours now.

In php I would have done this

$i = 0;
foreach ($input as $obj) {
   $array[$i]['subject'] = $obj;
   $i++;
}
$json = json_encode($array);

In Jquery i have this, where I have multiple form inputs with the same name, and I need to create a json input to submit safely in the form.

var i = 0;
$('.tekstforms').each(function(i, obj) {
   items[i]['emne'] = $(this).closest(".tekstforms").find("[name='emne']").val(); 
   i++;                                                             
});
alert(JSON.stringify(items));

But that’s not working

Answer

See this snippet:

You can take the attribute [name="emne"] as selector: $('.form-of-emne [name="emne"]').each()

var items = {};
$('.form-of-emne [name="emne"]').each(function(i) {
   items[i] = {
    ['emne']: $(this).val()
   }                                                         
});
console.log(JSON.stringify(items));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form class="form-of-emne">
  <input type="text" name="emne" value="abc">
  <input type="text" name="emne" value="xyz">
  <input type="text" name="emne" value="123">
</form>

Leave a Reply

Your email address will not be published. Required fields are marked *