Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values to a dropdown <select> box using JQuery

Tags:

jquery

I have a issue with populating values in a box using JQuery.

Instead of adding it underneath each other it adds it next to all other elements

my code

$('#pages option').append($('#t1').val());
like image 630
Elitmiar Avatar asked Oct 08 '09 08:10

Elitmiar


People also ask

How do I add a selection to a drop down list?

Select add() Method The add() method is used to add an option to a drop-down list. Tip: To remove an option from a drop-down list, use the remove() method.

How can I get the selected value of a drop down list with jQuery?

We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.

How do I select a selected box using jQuery?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.


2 Answers

I think you want

$('#pages').append($('#t1').val());

assuming pages is the id of your <select>. Also, $('#t1').val() should be an <option> element, not a value. Something like this

 var newOption = $('<option value="'+val+'">'+val+'</option>');
 $('#pages').append(newOption);

or

var newOption = $('<option>');
newOption.attr('value',val).text(val);
 $('#pages').append(newOption);

whichever is easier for you to read.

Here's a Working Demo

like image 65
Russ Cam Avatar answered Sep 28 '22 06:09

Russ Cam


You probably want something along the lines of

$("#pages").append("<option>"+$("#t1").val()+"</option>");

That will make and append an option to your select box

like image 42
peirix Avatar answered Sep 28 '22 07:09

peirix