'Get values in JSON object from html input text and label

I have a HTML by which currently getting the values of input elements in loop in an array.

But now I want this in json object with its label.

Below is my html:-

<div class="vendorDaterow">
    <div class="vendorName" id="dvVendorNameData">
        <label>SP Vender Name</label><span><input type="text" value="" name="nmVendorData" id="txtVendorName"/></span>
    </div>
    <div class="vendorFromDate">
        <label>From Date</label>
        <span class="datepicker">
        <input type="text" value="" name="spFromDate" id="spFromDate" class="dateClass"/>
        <i class="fa fa-calendar" aria-hidden="true"></i>
        </span>
    </div>
    <div class="vendorToDate">
        <label>To Date</label>
        <span class="datepicker">
            <input type="text" value="" name="spToDate" id="spToDate" class="dateClass1"/>
            <i class="fa fa-calendar" aria-hidden="true"></i>
        </span>
    </div>
</div>

and my js for the same

var arrVendorValues;
    arrVendorValues = []
    $(".vendorDaterow input").each(function () {
        var text = $(this).val();
        if (text) {
            arrVendorValues.push(text);
        }
    })

and output which I want is something like this

Vendor Name: ABC, ToDate: 10/10/2010, FromDate: 11/11/2017 Vendor Name: XYZ, ToDate: 10/10/2010, FromDate: 11/11/2017 Vendor Name: AAA, ToDate: 10/10/2010, FromDate: 11/11/2017



Solution 1:[1]

Kindly add a for attribute to the label and iterate over it

HTML

<div class="vendorDaterow">
  <div class="vendorName" id="dvVendorNameData">
    <label for="txtVendorName" class="text-label">SP Vender Name</label><span><input type="text" value="" name="nmVendorData" id="txtVendorName"/></span>
  </div>
  <div class="vendorFromDate">
    <label class="text-label" for="spFromDate">From Date</label>
    <span class="datepicker">
        <input type="text" value="" name="spFromDate" id="spFromDate" class="dateClass"/>
        <i class="fa fa-calendar" aria-hidden="true"></i>
        </span>
  </div>
  <div class="vendorToDate">
    <label class="text-label" for="spToDate">To Date</label>
    <span class="datepicker">
            <input type="text" value="" name="spToDate" id="spToDate" class="dateClass1"/>
            <i class="fa fa-calendar" aria-hidden="true"></i>
        </span>
  </div>
</div>

JS

$(document).ready(function() {
  var arrVendorValues = [];

  $(".text-label").each(function() {

    var key = $(this).text();
    var value = $("#" + $(this).attr('for')).val();
    arrVendorValues.push({
      key: key,
      value: value
    })
  })

  console.log(arrVendorValues)
});

And if you need it as standalone function

function getInputsAsJSON() {
  var arrVendorValues = [];
  $(".text-label").each(function() {

    var key = $(this).text();
    var value = $("#" + $(this).attr('for')).val();
    arrVendorValues.push({
      key: key,
      value: value
    })
  });
  return arrVendorValues;
}

You can trigger it in some click depending on your requirement.

Solution 2:[2]

You will need to create array of JSON objects. And then check the class of input element.

var arrVendorValues = [];
function generateData(){
  $(".vendorDaterow").each(function () {
    var allInputs = $(this).find("input");
    var objectToAdd = {};
    for(var i = 0; i < allInputs.length; i++){
      if(allInputs[i].name == "nmVendorData"){
        objectToAdd["VendorName"] = allInputs[i].value; 
      }
      else if(allInputs[i].name == "spFromDate"){
        objectToAdd["ToDate"] = allInputs[i].value;
      }
      else if(allInputs[i].name == "spToDate"){
        objectToAdd["FromDate"] = allInputs[i].value;
      }
    }
    arrVendorValues.push(objectToAdd);
  });
  console.log(arrVendorValues);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vendorDaterow">
                                        <div class="vendorName" id="dvVendorNameData">
                                            <label>SP Vender Name</label><span><input type="text" value="" name="nmVendorData" id="txtVendorName" /></span>
                                        </div>
                                        <div class="vendorFromDate">
                                            <label>From Date</label><span class="datepicker"><input type="text" value="" name="spFromDate" id="spFromDate" class="dateClass" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                        <div class="vendorToDate">
                                            <label>To Date</label><span class="datepicker"><input type="text" value="" name="spToDate" id="spToDate" class="dateClass1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                    </div>
                                    
<button onclick="generateData();">Generate Data</button>                                    

Solution 3:[3]

Use filter() to remove empties from collection and map() to create array

var data = $('.vendorDaterow input').filter(function(){
  return this.value;// filter out empty values
}).map(function(){
  var label = $(this).closest('div').find('label').text(),
        o ={};
  o[label] = this.value;
  return o;
}).get()

console.log(data)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vendorDaterow">
  <div class="vendorName" id="dvVendorNameData">
    <label>SP Vender Name</label><span><input type="text" value="123" name="nmVendorData" id="txtVendorName" /></span>
  </div>
  <div class="vendorFromDate">
    <label>From Date</label><span class="datepicker"><input type="text" value="" name="spFromDate" id="spFromDate" class="dateClass" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
  </div>
  <div class="vendorToDate">
    <label>To Date</label><span class="datepicker"><input type="text" value="456" name="spToDate" id="spToDate" class="dateClass1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
  </div>
</div>

Solution 4:[4]

Simply create one map for holding mapping for a display name and corresponding name html attribute. And in an iterator, push result in JSON object instead of an array. something like this,

<div class="vendorDaterow">
<div class="vendorName" id="dvVendorNameData">
    <label>SP Vender Name</label><span><input type="text" value="" name="nmVendorData" id="txtVendorName"/></span>
</div>
<div class="vendorFromDate">
    <label>From Date</label>
    <span class="datepicker">

    <input type="text" value="" name="spFromDate" id="spFromDate" class="dateClass"/>
    <i class="fa fa-calendar" aria-hidden="true"></i>
    </span>
</div>
<div class="vendorToDate">
    <label>To Date</label>
    <span class="datepicker">
        <input type="text" value="" name="spToDate" id="spToDate" class="dateClass1"/>
        <i class="fa fa-calendar" aria-hidden="true"></i>
    </span>
</div>

var map={nmVendorData:'Vendor Name', spFromDate:'FromDate', spToDate:'ToDate'}, 
result={};
$(".vendorDaterow input").each(function (a,b) {
    var text = $(this).val();
  result[map[$(b)[0].name]] = text;

})

Your result object will hold your intended result.

If you do want to collect multiple inputs from the user, just add some click handler for form submission and push result object into some array.

Solution 5:[5]

$(document).ready(function() {
    $('#btnSubmit').click(function() {
        var arrVendorValues = []
        var vendorDaterowObject = $(".vendorDaterow input");

        vendorDaterowObject.each(function() {
            var text = $(this).val();
            if (text) {
                arrVendorValues.push($(this).parents('.label-input').find('label').text() + ': ' + text);
            }
        });

        $('h3').text(arrVendorValues.join(', '));
    });
});

Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sunil Hari
Solution 2
Solution 3
Solution 4 Ravindra Thorat
Solution 5 Thulasiram