开发者

Converting form data to an object

I don't want to post the data to a ser开发者_如何转开发ver I want to pass it into a client side function that takes an object. What is the best way to do that?


You can just create your own object as such:

<form name='f1'>

<input type='text' name='firstname' />
<input type='text' name='lastname' />

</form>

window.onload = function()
{
    var Person = 
    {  
      'FirstName' : document.f1.firstname.value, 
      'LastName' : document.f1.lastname.value 
    }
}

A JSON object is just a regular Javascript object, because JSON is subset of Javascript.


If you're using jQuery you may want to look at the .serializeArray() function it provides as it does all you want in a single call. Using TJ's example;

<script type="text/javascript">
    $(function () {
        $('form[name="f1"]').submit(function() {
            var person = $(this).serializeArray();
            // Do what you will with 'person' now...
        });
    });
</script>
<form name="f1">
    <input type="text" name="firstname" />
    <input type="text" name="lastname" />
    <input type="submit" value="Submit" />
</form>

This way you don't have to manually build an object and declare a property for each field which helps avoid human error.

If for some reason you don't want to use jQuery then you could always look at the code to see the logic used and create your own function.


your question is the first on google, so here. Looks like the first way is the least amount of code.

var form = document.getElementById('iLoveLucy')

var obj1 = [...form.elements].reduce((_, el) => (_[el.name] = el.value, _), {})
console.log(obj1)

// another way
var obj2 = Object.assign({},
  ...[...form.elements].map(({name,value}) => ({[name]: value}))
)
console.log(obj2)

// a third way
var obj3 = new class {
  constructor() {
    [...form.elements].map(({name,value}) => this[name] = value)
  }
}
console.log(obj3)
<form id="iLoveLucy">
  <input name="fred" value="grumpy"/>
  <input name="wilma" value="tired"/>
  <input name="lucy" value="foolish"/>
  <input name="ricky" value="upset"/>
</form>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜