dieuvn3b
dieuvn3b

Reputation: 6114

Converting DOM elements into Objects

I have values of form as follow

<input name="Document[0][category]" value="12" type="text"> 
<input name="Document[0][filename]" value="abca.png"  type="text" >

I want to serialize it to an object by js or jquery.

Document[0]={
   category : 12
   filename : 'abca.png'
};

I try use serializeArray and parse to object but no good

Upvotes: 9

Views: 417

Answers (3)

Amadan
Amadan

Reputation: 198324

Low-tech method:

var Document = [];
var inputs = document.querySelectorAll('input');
Array.prototype.forEach.call(inputs, function(input) {
  var name = input.getAttribute('name');
  var prevProp = null;
  var obj = Document;
  name.replace(/\[(.*?)\]/g, function(m, prop) {
    if (prevProp) obj = obj[prevProp] || (obj[prevProp] = {});
    prevProp = prop;
  });
  obj[prevProp] = input.value;
});
console.log(Document);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name="Document[0][category]" value="12" > 
<input name="Document[0][filename]" value="abca.png" >
</form>

<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

EDIT: as guest271314 notes, using Document as a variable name might not be the greatest idea.

Upvotes: 5

ashishmohite
ashishmohite

Reputation: 1120

Check this out

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(function() {
    $('form').submit(function() {
        $('#result').text(JSON.stringify($('form').serializeObject()));
        return false;
    });
});
form {
    line-height: 2em;
}
p {
    margin: 5px 0;
}
h2 {
    margin: 10px 0;
    font-size: 1.2em;
    font-weight: bold
}
#result {
    margin: 10px;
    background: #eee;
    padding: 10px;
    height: 40px;
    overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>Form</h2>
<form action="" method="post">
First Name:<input type="text" name="Fname" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="Lname" maxlength="36" size="12"/> <br/>
Gender:<br/>
Male:<input type="radio" name="gender" value="Male"/><br/>
Female:<input type="radio" name="gender" value="Female"/><br/>
Favorite Food:<br/>
Steak:<input type="checkbox" name="food[]" value="Steak"/><br/>
Pizza:<input type="checkbox" name="food[]" value="Pizza"/><br/>
Chicken:<input type="checkbox" name="food[]" value="Chicken"/><br/>
<textarea wrap="physical" cols="20" name="quote" rows="5">Enter your favorite quote!</textarea><br/>
Select a Level of Education:<br/>
<select name="education">
<option value="Jr.High">Jr.High</option>
<option value="HighSchool">HighSchool</option>
<option value="College">College</option></select><br/>
Select your favorite time of day:<br/>
<select size="3" name="TofD">
<option value="Morning">Morning</option>
<option value="Day">Day</option>
<option value="Night">Night</option></select>
<p><input type="submit" /></p>
</form>
<h2>JSON</h2>
<pre id="result">
</pre>

found it here : http://jsfiddle.net/sxGtM/3/

Upvotes: 2

Nick Zuber
Nick Zuber

Reputation: 5637

Consider jQuery's serializeArray() function:

var results = $("#some_id").serializeArray();

This will give you an array of objects that you can work with in JavaScript. I don't think you're able to give these objects custom names, like you're trying to do here I'm assuming:

<input name="Document[0][category]" value="12" type="text"> 
             ^^^^^^^^^^^

If you need to name these results, I'd suggest serializing it with jQuery, then transferring that data to your own object.

Working Fiddle

Upvotes: 1

Related Questions