Alex Howes
Alex Howes

Reputation: 454

Function to create/add another select (dropdown) box

I need to find a away to insert/add a <select> (dropdown) box on click of a button. I want each click of the button to keep adding a new <select>.

Tested out some javascript/jquery functions and as I don't have much background in it, I'm having no luck!



Edit:
Sorry just kinda answered my own question with help from other questions to anyone wandering just view source code on this.

http://jsbin.com/ufuxuq/

that was pretty much what I wanted, but had to implement some php within the list so I had extra trouble with that, but it's all good now.

Thanks

Upvotes: 1

Views: 2660

Answers (3)

Alex Howes
Alex Howes

Reputation: 454

Sorry just kinda answered my own question with help from other questions to anyone wandering just view source code on this.

http://jsbin.com/ufuxuq/

that was pretty much what I wanted, but had to implement some php within the list so I had extra trouble with that, but it's all good now.

Thanks

Upvotes: 2

Adam Rackis
Adam Rackis

Reputation: 83366

You can create a <select> element (or any other element) with $("<select/>");
The append function can be used to append html into an item.

Combining them yields:

$("#buttonToAddDD").click(function () {
    var newDD = $("<select/>");
    $(newDD).append("<option>New Option 1</option>");
    $(newDD).append("<option>New Option 2</option>");
    $("#whereYouWantToAddNewDD").append(newDD);
});

<div id="whereYouWantToAddNewDD"></div>
<input type="button" id="buttonToAddDD" value="Add DD" />

Upvotes: 3

ppant
ppant

Reputation: 137

Dynamically creating/removing a html code is easy with JQuery as explained above by Adam. However keep caution to provide users with facility to remove them as well. Best way would be adding a id to the select box and provide a span/div with a close 'X' on clicking which either it could be removed completely

 $(document).ready(function(){
{
     $("#close").click({function(){

     $("#selectid").remove(); // to remove the select
     $("#selectid").hide(); //this would hide it but when submitted, the default/selected option shall still be submitted
     $("#close").remove();
     }):
});

Upvotes: 1

Related Questions