zamil
zamil

Reputation: 1930

Populate dropdown value looping thru a set of links

I want to loop thru the a's inside a div and populate the option value of the select box just above it with the href value of the a in the order it appears using jQuery

This is my code

<div class="results_filter">
    <label for="sort" class="dropdown_label">Sort by:</label>
    <select name="sort" id="sort" class="custom_select">
        <option value="">Make</option>
        <option value="">Year of Manufature</option>
        <option value="">Price</option>
    </select>
    <a href="/cars/index/sort:make_id/direction:asc">Make</a><a
        href="/cars/index/sort:model_year/direction:asc">Year of
    Manufature</a><a href="/cars/index/sort:asking_price_from/direction:asc">Price</a>
</div>

I tried this but it is not working

$(document).ready(function () {
    $('div.results_filter > a').each(function (n) {
        $("#sort > options" + n).val($(this).text());
    });
})

Any help is appreciated. Please don't ask me why this awkward method. :)

Upvotes: 0

Views: 86

Answers (1)

Reactgular
Reactgular

Reputation: 54811

You have to create new option element for each one and append them to the select.

var sort = $("#sort");
$("div.results_filter > a").each(function() {
    var option = $("<option>").attr("value",$(this).attr("href")).text($(this).text()); 
    sort.append(option);
});

http://jsfiddle.net/stwRW/

Upvotes: 1

Related Questions