1

i have a string like this :

string_data = "<option value='1'>ahmad</option><option value='2'>mohammad</option><option value='3'>ali</option>"

now i want get the value of value attribute of options and alert it. for this i write this :

$(string_data).contents()
.each(function(){
    value   =   $(this).attr('value');
    text    =   $(this).text();
    alert(value);
});

but this code return undefined for all of them .
in Addition string_data is a string that i get it from a php script with Ajax via $.post() jQuery method.
i am using jquery 1.6 .

3 Answers 3

3

The contents() method retrieves the children of your elements which in your case are the text nodes. Omit that method call to iterate through <option> elements:

$(string_data).each(function(){
    value   =   $(this).attr('value');
    text    =   $(this).text();
    alert(value);
});
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure it's valid to load the string_data like this, when jQuery expects an identifier. It should probably be more like:

$('#some_hidden_select').html(string_data).find("option")
.each(function(){
    value   =   $(this).attr('value');
    text    =   $(this).text();
    alert(value);
});

Comments

0

Try:

$(string_data).find("option")
.each(function(){
    value   =   $(this).attr('value');
    text    =   $(this).text();
    alert(value);
});

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.