user2514691
user2514691

Reputation: 39

Create drop down on the fly

I have looked all over for an answer to this, but cant seem to find a definitive answer.

I want to be able to display a dropdown, populated from MySQL with PHP and have next to it a '+' or something that will, when clicked on, create another dropdown with the same data as the first.

In this way, the user can add as many dropdowns as they want. There will be around 25 items in each dropdown. I'm open to JS,JQuery etc. - just need to get it done!

I'd appreciate any and all help.

Rob

Edit

Had a night sleep - so let's try again!
Based on @adeno code I cam up with this:

?>

<!doctype html>
<html lang="en">
 <head>
 <title>Document</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>

<body>

<form action = 'testselectprocess.php' method='POST'>

<div>
<select id='test' name='test0'>
    <option name='first' value = '1'>option 1</option>
    <option name='second' value = '2'>option 2</option>
    <option name='third' value = '3'> option 3</option>
</select>
<select id='counting' name='count0'>
    <option name='first' value = '1'>1</option>
    <option name='second' value = '2'>2</option>
    <option name='third' value = '3'>3</option>
</select>
</div>

<button  type='button' class="more">Add another...</button>

<script>
var c=0;
$('.more').on('click', function() {
//alert(c);
$(this).before( $(this).prev().clone());
$('#test').attr('name', 'test'+ c)
$('#counting').attr('name', 'count'+ c)
c++;
});


</script>

<input type="submit" value="Add this." name="what">

</form>

 </body>
</html>

Trouble is - after the first 'Add another...' press, the id numbers don't increment. Looking at it with IEs DOM explorer the id increments once only. Wish I knew how to cut and paste in the DOM explorer but I only seem to be able to copy one element.

Upvotes: 0

Views: 667

Answers (1)

adeneo
adeneo

Reputation: 318302

Depends on the markup, but in principle it's pretty straight forward, you create a button that when clicked clones the select and inserts the clone

$('.more').on('click', function() {
    $(this).before( $(this).prev().clone() )
});

FIDDLE

Upvotes: 4

Related Questions