最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert input fields to Json in javascript - Stack Overflow

programmeradmin4浏览0评论

I would like to get a json result from my input fields.

Json Result

[{ScheduledVisit: "09/06/2017 12:00 AM", Company: "ABC Corp.", ContactPerson: "Someone"}]

The reason for that is because I want it to fit my class of

public class ScheduleVisit
{
    [Required(ErrorMessage = "* Required")]
    public DateTime ScheduledVisit { get; set; }
    public string Company { get; set; }
    public string ContactPerson{ get; set; } 
}

I do not want to use the $("inputForm").serialize(); because I want to learn how to do this manually.

Below is my input form

<div class="col_half">
    <input type="text" name="ScheduledVisit" placeholder="Scheduled Visit" class="sm-form-control border-form-control datetimepicker" id="ScheduledVisit" />
</div>

<div class="col_half col_last">
    <input type="text" name="pany" class="sm-form-control border-form-control" placeholder="pany" id="pany" />
</div>

<div class="col_two_third">
    <input type="text" name="contactPerson" placeholder="Contact Person" class="sm-form-control border-form-control" id="contact" /> 
</div>

Please help. Thank you.

I would like to get a json result from my input fields.

Json Result

[{ScheduledVisit: "09/06/2017 12:00 AM", Company: "ABC Corp.", ContactPerson: "Someone"}]

The reason for that is because I want it to fit my class of

public class ScheduleVisit
{
    [Required(ErrorMessage = "* Required")]
    public DateTime ScheduledVisit { get; set; }
    public string Company { get; set; }
    public string ContactPerson{ get; set; } 
}

I do not want to use the $("inputForm").serialize(); because I want to learn how to do this manually.

Below is my input form

<div class="col_half">
    <input type="text" name="ScheduledVisit" placeholder="Scheduled Visit" class="sm-form-control border-form-control datetimepicker" id="ScheduledVisit" />
</div>

<div class="col_half col_last">
    <input type="text" name="pany" class="sm-form-control border-form-control" placeholder="pany" id="pany" />
</div>

<div class="col_two_third">
    <input type="text" name="contactPerson" placeholder="Contact Person" class="sm-form-control border-form-control" id="contact" /> 
</div>

Please help. Thank you.

Share Improve this question asked Aug 11, 2017 at 4:03 Ibanez1408Ibanez1408 5,07812 gold badges73 silver badges130 bronze badges 1
  • "I would like to get a json result from my input fields." Is requirement to create valid JSON from <input> .name and .values, or is requirement to create a JavaScript object? – guest271314 Commented Aug 11, 2017 at 4:25
Add a ment  | 

5 Answers 5

Reset to default 3

You can iterate <form> .elements, set each .name and .value as property and values of a FormData() object which can be submitted to server using fetch() or XMLHttpRequest(), or set properties and values at a JavaScript object which can be passed to JSON.stringify()

const form = document.forms[0];

form.onsubmit = e => {
  e.preventDefault();
  const fd = new FormData();
  const props = {};
  for (let element of form.elements) {
    if (element.type !== "submit") {
      props[element.name] = element.value;
      fd.append(element.name, element.value);
    }
  }
  
  for (let [key, prop] of fd) {
    console.log(key, prop)
  }
  
  const json = JSON.stringify(props);
  console.log(json);
}
<form>
  <div class="col_half">
    <input type="text" name="ScheduledVisit" placeholder="Scheduled Visit" class="sm-form-control border-form-control datetimepicker" id="ScheduledVisit" />
  </div>

  <div class="col_half col_last">
    <input type="text" name="pany" class="sm-form-control border-form-control" placeholder="pany" id="pany" />
  </div>

  <div class="col_two_third">
    <input type="text" name="contactPerson" placeholder="Contact Person" class="sm-form-control border-form-control" id="contact" />
  </div>
  <input type="submit">
</form>

You can make object constructors that resemble your backend code. Here, I am serializing the inputs into a scheduleVisit object.

function scheduleVisit(obj) {
  this.scheduledVisit = obj.scheduledVisit;
  this.pany = obj.pany;
  this.contactPerson = obj.contactPerson;
}

document.getElementById('button').addEventListener('click', function() {
  var scheduledVisit = document.getElementById('ScheduledVisit').value;
  var pany = document.getElementById('pany').value;
  var contactPerson = document.getElementById('contact').value
  var visit = new scheduleVisit({
    scheduledVisit: scheduledVisit,
    pany: pany,
    contactPerson: contactPerson
  });

  console.log(JSON.stringify(visit));
});
<div class="col_half">
  <input type="text" name="ScheduledVisit" placeholder="Scheduled Visit" class="sm-form-control border-form-control datetimepicker" id="ScheduledVisit" />
</div>

<div class="col_half col_last">
  <input type="text" name="pany" class="sm-form-control border-form-control" placeholder="pany" id="pany" />
</div>

<div class="col_two_third">
  <input type="text" name="contactPerson" placeholder="Contact Person" class="sm-form-control border-form-control" id="contact" />
</div>

<button id=button>Submit</button>

You can assign the value of your inputs to an object manually. See below snippet for example. You can then serialize the object into a JSON formatted string.

let obj = {};
obj.ScheduledVisit = document.getElementById("ScheduledVisit").value;
obj.Company = document.getElementById("pany").value;
obj.Contact = document.getElementById("contact").value;
console.log(obj);
let jsonStringObj = JSON.stringify(obj);
console.log(jsonStringObj);
<div class="col_half">
    <input type="text" name="ScheduledVisit" placeholder="Scheduled Visit" class="sm-form-control border-form-control datetimepicker" value="testVisit" id="ScheduledVisit" />
</div>

<div class="col_half col_last">
    <input type="text" name="pany" class="sm-form-control border-form-control" placeholder="pany" value="testCompany" id="pany" />
</div>

<div class="col_two_third">
    <input type="text" name="contactPerson" placeholder="Contact Person" class="sm-form-control border-form-control" value="testContact" id="contact" /> 
</div>

Using pure javascript you can do JSON.stringify(yourInputValu) to convert any javascript object to JSON

If your input form is that simple and you don't want a more generic solution, you could do it pretty easily with:

function get( id ) { return document.getElementById(id).value; }

var json = JSON.stringify({
    ScheduledVisit: get('ScheduledVisit'),
    Company: get('pany'),
    Contact: get('contact')
});
发布评论

评论列表(0)

  1. 暂无评论