Essentially this is what I am trying to do
I have a button, by triggering it, a dropdown of books is displayed to the user. With each trigger, a new dropdown is loaded.
The way I have kept loading them to the user is by cloning a hidden div. Like so
<form action="POST">
<div id="books"></div>
<button onclick="addBook()"></button>
<input type="submit" value="Submit">
</form>
<select id="book" name="books[]" style="display: none;">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<script>
$count = 0;
function addBook() {
$clone = $("#book").clone().show();
clone.find("#book").attr('id','book-' + $count);
clone.appendTo("#books");
$count += 1;
}
For example, after clicking the button 3 times, this will be my html display (i have obviously changed the selected value)
<form action="POST">
<div id="books">
<select id="book-0" name="books[]">
<option value="A">A</option>
<option value="B">B</option>
<option value="C" selected>C</option>
</select>
<select id="book-1" name="books[]">
<option value="A">A</option>
<option value="B" selected>B</option>
<option value="C">C</option>
</select>
<select id="book-3" name="books[]">
<option value="A" selected>A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
<button onclick="addBook()"></button>
<input type="submit" value="Submit">
</form>
<select id="book" name="books[]" style="display: none;">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
The issue is now.. when i hit submit, I'm collecting their data using the name field (i.e. books[]) which should be something like books[C, B, A]. However when I print the books[] values, I get books[C, B, A, A]. The last A seems to be coming from the hidden div! eventhough it is hidden.
var books = $("select[name='books[]']").map(function(){return $(this).val();}).get();
console.log(books);
I have tried disabling, making it readonly etc etc, but everytime the value of the hidden div seem to be attached to my element of arrays (which i don't want)