Okay here's the thing.
When you change your option
you have to go trough a couple of things.
First you get the Data of the Option and make it in a Array.
// Select the text of the chosen option
var text = $(this).children(":selected").html();
// Create a regex to split the string
var regex = new RegExp(" *");
// Make an array out of the string
// The cleanArray() function is in the JSFiddle
var array = cleanArray(text.split(regex));
Now you have an Array of the Values you want to add.
Next step is to create the HTML you want to add to your tbody
.
// Create a new <tr> to append to the tbody
var newRowHTML = "<tr>";
$.each(array,function(){
newRowHTML += "<td>"+this+"</td>";
});
newRowHTML += "<tr>";
Now loop trough your td
's and see if the ID of the Option you clicked is alreay there.
var alreadyInTable = false;
$.each($("tbody tr > td:first-child"),function(){
if(array[0] == $(this).html()){
// If this ID is alreay in the table set the bool to true
alreadyInTable = true;
}
});
And add the HTML.
if(alreadyInTable == false){
$("tbody #select").before(newRowHTML);
}
Important Notes: If you do not read and apply these dependencies the code will not work!
To use this you cannot have any whitespaces or new lines in your option. This means it has to look like:
<option>thecompletetextwithoutanywhitespacesbetweenthedata</option>
Also you have to add id="select"
to the tr
containing the select, as it is the one after where you display your data, so you can use $("tbody #select").before(newRowHTML)
as shown before.
You have to make the "+ Add new Line" selected
as you can see in the Fiddle's HTML, since the new Rows only get added on a change
of the select
, so you cannot just click the row you have already selected as it does not change which one you have selected.
And here is a complete JSFiddle!