[eluser]chadtomkiss[/eluser]
*UPDATE*
Wanted the div wrapper in the view, but that wraps the remove button in a sep div, so isn't alongside the input.
Will post an update when I've fixed it
Hi guys,
Have been struggling with this problem for most of today, and think I'm at a stage where I'm happy with it, couldn't find anything on the interwebs, so thought I'd share what I came up with
What it looks like
The problem:
Adding field inputs so that users can customise the options in a dropdown field.
The solution:
View
We have an input which will be the initial field in the dropdown, and then a button to add more options
Code:
<div id="custom_options">
<?php echo form_label("Default Option", "custom_field_options[default]"); ?>
<?php echo form_error("custom_field_options[default]"); ?>
<input type="text" id="custom_field_options[default]" name="custom_field_options[default]" value="<?php echo set_value('custom_field_options[default]'); ?>" />
<input type='button' class='addOption' value='add' />
<?php
if ($custom_field_options)
{
foreach($custom_field_options as $option)
{
echo $option;
}
}
?>
</div>
jQuery
We want to add a click handler that adds both the input field, and a remove button
Code:
$('.addOption').click(function() {
var input = "<div class='option'><input type='text' id='custom_field_options[]' name='custom_field_options[]' value='' />";
input += '<input type="button" value="remove" class="removeOption" name="removeOption" /></div>';
$('#custom_options').append(input);
});
We also want to add a live handler for every remove button to remove the closest input.
Code:
$('.removeOption').live('click',function() {
$(this).closest('.option').remove();
});
Controller
Firstly, we want the default option to be required so set the rules
Then we want to capture the extra inputs so that they can be re-populated with their values incase of a form error.
Code:
$this->form_validation->set_rules('custom_field_options[default]', 'default option', 'required');
$this->form_validation->set_rules($rules);
// Array is sliced so that we can skip the default input so that it doesn't become duplicated.
$this->load->helper('form');
foreach(array_slice($this->input->post('custom_field_options'), 1) as $option)
{
$data['custom_field_options'][] = "<div class='option'>";
$input = array(
'name' => 'custom_field_options[]',
'id' => 'custom_field_options[]',
'value' => $option
);
$data['custom_field_options'][] = form_input($input);
$input = array(
'class' => 'removeOption',
'value' => 'remove',
'type' => 'button'
);
$data['custom_field_options'][] = form_input($input);
$data['custom_field_options'][] = "</div>";
}
Hope this will help someone
Cheers,
Chad