Reputation: 575
I'm looking for a way of replacing .val();
in jQuery with something like .array
or .object
. So instead of getting only the value of a drop down, i can return the full array for the selected value.
I have a drop down which allows a user to select multiple 'gameTypes', i'm outputting this to the screen and when the user clicks next the content of these 'gameTypes' should be sent as a JSON request.
The code i'm currently using is below however it only returns the 'gametype' name, so when i run the code i get 'RPG' in the console. What i need is the full object, so RPG, publishers, games etc.
Ive looked at the API documentation in jQuery and can't find a way of doing it, is it possible with jQuery?
Js Code:
$("#nextbutton").click(function () {
var datatosend = {
gametypes: [],
market: [] //This is populated using the same method however i don't need the whole object, just the name so this works
};
$("#comboGameType").find(":selected").each(function() {
var str = $(this).val();
datatosend.gametypes.push(str);
console.log(str);
});
});
JSON example:
{
"games": [{
"gameType": "RPG",
"publishers": [{
"publisher": "Square",
"titles": [{
"title": "Final Fantasy",
"gameReleases": [ 2006, 2008, 2010, 2012, 2013, 2014 ]
}]
}]
}]
}
The html is pretty standard, it's populated through js
<select id="comboGameType" class="selectpicker" multiple> </select>
JS to handle changes to drop down and display selections:
$('#comboGameType').change(function () {
var values = $('#comboGameType').val();
var parsedData = JSON.parse($myData);
for (var i = 0; i < values.length; i += 1) {
$('#output').append("<div>" + values[i] + "</div>")
}
});
Heres a fiddle to show as an example - when you view console see the value of the drop down is returned, however i'm trying to return the FULL object (so everything in RPG for example) http://jsfiddle.net/2Ma7U/
Upvotes: 0
Views: 91
Reputation: 3417
You can use jQuery data to store the entire object and retrieve it later.
$(parsedData.genres).each(function (i) {
$("#pubCombo").append($("<option/>", {
val: this.genre,
html: this.genre,
data: this
}));
});
$("#next").click(function () {
var datatosend = {
gametypes: [],
market: []
};
$("#pubCombo").find(":selected").each(function() {
var obj = $(this).data();
datatosend.gametypes.push(obj);
console.log(obj);
});
});
Updated fiddle http://jsfiddle.net/2Ma7U/1/
Upvotes: 1