Welcome Guest, Not a member yet? Register   Sign In
Dropdown with option of 'Add New' and save new item to DB

[eluser]Victor Michnowicz[/eluser]
If you have some HTML in your page like this:

<form method="post" id="new_item_form" action="/welcome/add">
<input type="text" name="new_item" id="new_item" />
<input type="submit" value="Add New Item" />

Then put some jQuery in your page like:

$('#new_item_form').submit(function(e) {
$.post($(this).attr('action'), $(this).serialize(),
if (data == 'true') {
// Load new dropdowns
$('#div_around_my_dropdown').load('/welcome #div_around_my_dropdown', function() {
alert('Item Added');
else {
alert('ERROR: ' + data);

Then in the "welcome" controller add the "add" method:

public function add()
$new_item = trim($this->input->post('new_item'));

if ($new_item)
$data = array(
name => $new_item
$this->db->insert('my_table', $data);
echo 'true';
echo 'false';

I'm sure there are some errors in my code, but it should get you started. Basically we are using jQuery to jQuery.post() some data to our "add" method. This method inserts the user-inputed text into the database. The method then echos "true." jQuery then checks that our DB insert succeeded. If it worked, it then uses the .load() function to grab a newer version of the page (the one with the new option we just added).

There are tons of ways to skin this cat. Another way may is to return the insert ID from the database instead of just "true" or "false." We can then use this insert ID to add a new option to the select input. This would be an alternative to the .load() function (and may be a bit faster?)

$('#my_select_input').append('<option value="' + data + '">' + $(new_item).val() + '</option>');

If you wanted to get fancy you could look into json_encode() too.

Messages In This Thread
Dropdown with option of 'Add New' and save new item to DB - by El Forum - 12-27-2010, 08:30 AM

Theme © iAndrew 2016 - Forum software by © MyBB