Reputation: 37
function createJSON() {
var data = new Object();
$("input[class = detail_text]").each(function() {
data[$(this).attr("name")] = $(this).val();
jsonString = JSON.stringify(data);
});
console.log(jsonString);
}
I am trying to get the value of input in an innerHTML. This input fields are multi valued. How to get these attributes? In my code, the last one is the only one that get save. I am new to this. Thanks.
<div class="window task" style="left: 120px; top:200px; display:none;" data-nodetype="task" id="taskcontainer0">
<div class="ctrl_container">
<div class="button_remove">x</div>
</div>
<div class="details_container">
<label class="detail_label">Name</label>
<input type = "text" class="detail_text" name = "task"/><br/>
<label class = "detail_label">Description</label>
<input type = "text" class ="detail_text" name = "msg">
</div>
</div>
This is the html code.
Upvotes: 1
Views: 530
Reputation: 1074385
If the fields are multi-valued, you probably want to store arrays for each name, see inline comments:
function createJSON() {
var data = {}; // {} is usually better than new Object
$("input[class = detail_text]").each(function() {
var $this = $(this),
name = $this.attr("name");
// Is there already a value saved for this name?
if (!data.hasOwnProperty(name)) {
// No, create a blank array
data[name] = [];
}
// Add this value to the array of values for this name
data[name].push($this.val());
});
jsonString = JSON.stringify(data);
console.log(jsonString);
}
Also note that you probably meant to do the JSON.stringify
after the loop.
Or if you only want an array if you have multiple values for a given name
, then:
function createJSON() {
var data = {}; // {} is usually better than new Object
$("input[class = detail_text]").each(function() {
var $this = $(this),
name = $this.attr("name");
// Is there already a value saved for this name?
if (!data.hasOwnProperty(name)) {
// No, save this value
data[name] = $this.val();
}
else {
// Yes, is it an array?
if (!Array.isArray(data[name])) {
// No, make it one
data[name] = [data[name]]; // Wraps the existing value in an array
}
// Add this value to it
data[name].push($this.val());
}
});
jsonString = JSON.stringify(data);
console.log(jsonString);
}
Array.isArray
is an ES5 thing, but the shim is trivial:
if (!Array.isArray) {
Array.isArray = (function() {
var toString = Object.prototype.toString;
return function(arg) {
return toString.call(arg) === "[object Array]";
};
})();
}
Side note: You almost never want to use an attribute selector ("input[class = detail_text]"
) for selecting by class, because of course elements can have multiple classes. Instead, use a class selector: "input.detail_text"
Upvotes: 3