Question

I've already seen other examples here on SO but none of them fit my problem.

I have a function that receives a select element, and I need it to spit out a JSON formatted string.

Example:

foo = buildOptionStructure($('.select-test'));

// Returns string of JSON formatted option data from select
// options in element.
function buildOptionStructure(selectElement) {
    options = "[";
    selectElement.find('option').each(function(option, i) {
        console.log(this); // Return my html in console.
        console.log(option); // Return a zero based index!
        console.log("I VALUE: " + option); // Returns same zero based index!
        options += "{";
        options += "name:'" + option.text() + "'";
        options += "},";
    });
    options += "]"

    return options;
}

I just need to build a string out of the options in the given select element. What am I missing here?

Was it helpful?

Solution

function buildOptionStructure(selectElement) {
    var options = [];
    selectElement.find('option').each(function(k,v) {
        options.push({name: $(this).val()});        
    });
    return options
}

var foo = buildOptionStructure($('.select-test'));

console.log(foo);

To get the JSON string, you can use JSON.stringify(foo).

FIDDLE

OTHER TIPS

You're accessing the index when you attempt to use option.text() To access the text of the element, use this:

    options += "name:'" + $(this).text() + "'";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top