views:

56

answers:

2

Sorry guys, I should have posted the script directly without cleaning it. Please check the updated script, it should now clear things up. Thanks!

Consider the following JavaScript :

    var selected = 0;
    var options = 0;

    $('.newListSelected').each(function() {

        selected = $(this).children('.selectedTxt');
        selected = selected.text();

        /* Everything before this line works completely fine */

        options = $(this).prev();

        options.find('option[value=' +selected+ ']').attr('selected', 'selected');

    }).remove();

And HTML :

<select name="type[]" style="display: none;">
    <optgroup>
        <option value="none">Select</option>
    </optgroup>
    <optgroup label="First Group">
        <option value="1">One</option>
        <option value="2">Two</option>
    </optgroup>
    <optgroup label="Second Group">
        <option value="10">Ten</option>
        <option value="20">Twenty</option>
    </optgroup>
</select>

<div class="newListSelected">
    <div class="selectedTxt">20</div>
    <ul class="newList">
        <!-- Other stuff here -->
    </ul>
</div>

What I'm trying to do actually is adding the selected attribute to the corresponding select option that has the same value as the text in .selectedTxt. In the code above, it should add selected="selected" to <option value="20">Twenty</option>.

However its not performing as expected, I also tried adding alert(option); below prev(); but it didn't output anything useful.

Thanks.

+4  A: 

The Javascript works fine, as can be seen here: http://jsfiddle.net/4HsXp/

If you need to be able to select multiple items in a select element, you need to set the multiple and size attribute, like this:

<select multiple="multiple" size="2">
    <option>1</option>
    <option>2</option>
</select>

See: http://reference.sitepoint.com/html/select


Edit:

Attaching console.log statements to the new code still does not any problem. Running it on jsfiddle gave me the correct output:

jQuery(select)
Original Value: none
New Value: 20
Yi Jiang
...why didn't I think of that, oh well +1 :)
Kristoffer S Hansen
I've updated my code, sorry for the confusion!
@user Updated, and *still* nothing seems to be wrong. Can you elaborate on what appears to be the problem?
Yi Jiang
@Yi Jiang Wired.. I use Firebug to check the elements but couldn't see any option that contain `selected="selected"` after executing the script.
A: 

I'm not sure what you are trying to do, but why couldn't you just select all option elements with proper selectors? If you want to select only some options, then you have to add extra selector attrbiutes.

$('select option').each(function() {
    $(this).attr('selected', 'selected');
});
newbie
I've updated my code, sorry for the confusion!