David
David

Reputation: 1191

add a <select> with option values from database to a form with jQuery dynamically

With PHP I echo out a <select> with options to a form based on database values like this:

/* SQL Stuff */

$sql = mysql_query("SELECT id, name FROM myTable");

echo "<select>";

while ($row = mysql_fetch_assoc($sql)) {

    echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}

echo "</select>";

Is it possible with jQuery to have an "Add" button, which will generate the same <select> with the same <option> values to the form?

Upvotes: 1

Views: 2551

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

You don't give html in your question. So its not possible to hit to correct point. But I think you need something like following. It is just an sample.

HTML

<div id="some_target">
  <select>
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
  </select>
</div>
<input type="button" id="add_button" value="Add more">

jQuery

$('#add_button').on('click', function() {
  var selectClone = $('select:first').clone(true);  // make a copy of select
  $('#some_target').append(selectClone);    // append to clone select
});

Upvotes: 1

Related Questions