javascript - Loop through a <select> tag and append the content to JSON object -
i have <select>
tag on site contains multipe choises options. need append these options in <select>
tag existing json object.
my html code:
<form onsubmit="return false;" role="form"> <div class="form-group"> <label for="groupselector">group:</label> <select class="form-control" id="groupselector"> <option value="guests">guests</option> <option value="members">members</option> <option value="vips">vips</option> <option value="mods">mods</option> <option value="admins">admins</option> <option value="owners">owners</option> </select> </div> <div class="form-group"> <input type="text" placeholder="prefix..." class="form-control" id="groupprefix" /> </div> <div class="form-group"> <select multiple class="form-control" style="min-height: 170px;" id="grouppermissions"> <option>permission.node.1</option> <option>permission.node.2</option> <option>permission.node.3</option> <option>permission.node.4</option> <option>permission.node.5</option> </select> </div> <div class="text-right"> <input type="submit" value="send" class="btn btn-primary" /> <button value="save" class="btn btn-default" onclick="save_field_data('perm_manager');">save</button> </div> </form>
you can see in html <select>
field id of "grouppermissions"'
here need do: have json object want append <option>
values <select>
field nested inside json object. want json object like:
{ "selected_group":"mods", "prefix":"[moderator]", "permissions": { "node": "permission.node.1", "node": "permission.node.2", "node": "permission.node.3", "node": "permission.node.4", "node": "permission.node.5", } }
im looking way append child elements (the <option>
tags) <select>
field, , append them json object , have shown above.
this current javascript saves field values. , need append options in here before sending off storage on server.
var permnodes = {}; $('#grouppermissions option').each(function(){ permnodes.push( {"node": this.value} ); }); var perm_manager_data = { selected_group: $("#groupselector").val(), prefix: $("#groupprefix").val(), permissions: permnodes }; $.ajax ({ type: "post", datatype : 'json', async: false, url: 'data/save_data.php?file=permissions_manager', data: { data: json.stringify(perm_manager_data) }, success: function() {alert("field data saved successfully!"); }, failure: function() {alert("an error occured trying save field data!");} });
1 thing first cannot have multiple keys in object notation same name. @ least needs change names like: node1, node2 etc. , trying push elements object.
2 thing can add options javascript object nodes instead of array. this.
permnodes["node"+i] = this.value;
update 1 if want permissions , array in json output, change have make is:
var permnodes = [];
instead of
var permnodes = {};
Comments
Post a Comment