Just want to ask if it is possible to use PHP in my question so here it is. I am making a simple search code wherein the user will search for example "John" now many John's will appear on a table. In each row there will be a button named "add to list". If the user clicks the add button, the details of John will be put inside the select multiple like this.
<select multiple class="form-control">
<option>John</option>
</select>
now if I click another for example "Kevin" it will become...
<select multiple class="form-control">
<option>John</option>
<option>Kevin</option>
</select>
once the select multiple has been populated I will print it(thats another story now). So basically my question is how do I add values to <select multiple> by pressing the button "add" and get the ID's of the options inside select multiple for retrieval? I think i'm making my question complicated and i'm very sorry for my bad english. I've tried if, for, do-while, while but i cant seem to get the logic.I hope you understand thank you very much!
We can use jQuery so the page won't have to reload when a name/button is clicked/select.
Example code:
<!-- HERE ARE THE LIST OF NAMES TO BE ADDED IN THE SELECT FIELD -->
<table>
<tr>
<td>Kevin</td>
<td><button class="names" value="Kevin">Add to List</button></td>
</tr>
<tr>
<td>John</td>
<td><button class="names" value="John">Add to List</button></td>
</tr>
</table>
<!-- AND HERE IS THE SELECT FIELD THAT YOU WANT TO BE POPULATED -->
<select multiple class="form-control" id="select-names">
<option disabled selected>Select first from the table of names</option>
</select>
And we have to create a script that when a button is selected, it will be added to the <select> field. You have to download first jQuery here.
<script src="jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY FILE DEPENDING ON THE VERSION OF jQuery YOU HAVE DOWNLOADED -->
<script type="text/javascript">
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$(".names").click(function(){ /* WHEN A BUTTON IS CLICKED */
var names = $(this).val(); /* GET THE VALUE OF THAT BUTTON */
$(this).closest("tr").fadeOut(200).hide(); /* HIDE THIS ROW */
var newOption = $('<option></option>'); /* CREATE AN OPTION */
newOption.val(names); /* SET THE VALUE OF THIS OPTION WITH THE VALUE OF THE SELECTED NAME */
newOption.html(names); /* SET THE CONTENT OF THIS OPTION */
$("#select-names").append(newOption); /* APPEND THIS OPTION TO THE SELECT FIELD */
});
});
</script>
If you want a proof, check this JSfiddle.
But if you also want a database interaction, post your database structure, explain the schema and give us more of the code you are working on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With