Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery create select options using loop

Tags:

jquery

Im trying to create select box using jquery but the links populates randomly so I need to loops thru links and grab it to make select box, here is my code any idea how to use a short hand/loop? Thanks

HTML:

<p>
    <a href="#">option1</a>
    <a href="#">option2</a>
    <a href="#">option3</a>
</p>

<select  id="select"></select>

JS:

$.fn.populate = function() {
    var option1 = $('p a:eq(0)').text();
    var option2 = $('p a:eq(1)').text();
    var option3 = $('p a:eq(2)').text();
  $(this)
    .append('<option value="">' + option1 + '</option>')
    .append('<option value="">' + option2 + '</option>')
    .append('<option value="">' + option3 + '</option>')
}

$('#select').populate();

Fiddle

like image 346
test Avatar asked Oct 17 '13 20:10

test


3 Answers

var $this = $(this);

$('p a').each(function(){
    $this.append('<option value="">' + $(this).text() + '</option>');
});

http://jsfiddle.net/QgCqE/1/

like image 148
James Montagne Avatar answered Nov 15 '22 07:11

James Montagne


http://jsfiddle.net/kasperfish/RY3U9/4/

var selectbox=$("#select");//cache our slectbox, so jquery doesn't have to look for it in every loop.

$('p > a').each(function(){//select all a tags in p (loop through them)
    var text=$(this).text();//cache the link text in a variable because we need it twice.
    selectbox.append($('<option>').text(text).val(text));//add new option with value en text to selectbox
})
like image 38
kasper Taeymans Avatar answered Nov 15 '22 07:11

kasper Taeymans


A Cleaner and more jQuery-oriented solution of James Montagne's answer:

$this.append( $('<option/>').val('').text($(this).text()) );

or the alternative with properties mapping:

$this.append($("<option/>", {
    value: '',
    text: $(this).text()
}));
like image 27
a11r Avatar answered Nov 15 '22 05:11

a11r