1

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?

2
  • You're missing a quote in that code. You also aren't returning anything from your function. Commented Feb 22, 2014 at 23:51
  • @james: I edited the question with the missing quote. Commented Feb 22, 2014 at 23:55

2 Answers 2

2
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

Sign up to request clarification or add additional context in comments.

3 Comments

Nice. He needs a json string though... how do you get the array into a json string?
I understand. I was suggesting you edit the question for the OP's benefit, not mine...
I added it to my answer as well. Thanks for the tip!
1

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() + "'";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.