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
var $this = $(this);
$('p a').each(function(){
$this.append('<option value="">' + $(this).text() + '</option>');
});
http://jsfiddle.net/QgCqE/1/
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
})
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()
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With