Add options to a DropDownList using jQuery in Code Igniter
I'm looking for a way to add a custom option to a drop down select list with Jquery. So the user would click the drop down, and be presented with a list of options, the last being 'add other...' o开发者_运维知识库nce they click this they can then enter an option of their own (through a pop up, popover, directly inline or however.)
There's the post below that explains it, however, I'm using CI which has the options as an array etc. How can I apply this in Code Igniter?
How do I add options to a DropDownList using jQuery?
Thanks!
p.s. My js knowledge isn't great.
Try this on for size:
http://jsfiddle.net/Fh5Bz/1/
HTML:
<select id="myselect">
<option>hello</option>
<option>world</option>
<option>Add other...</option>
</select>
<div id="addother">
<input type="text" id="addother_input" />
</div>
CSS:
#addother {
display:none;
}
JS:
$(document).ready(function() {
$('#myselect').change(function(e) {
if ($(this).val() == "Add other...") {
$('#addother').show();
//set the input back to an empty string
$('#addother_input').val('');
} else {
$('#addother').hide();
}
});
});
Edit: Sorry, missed your line about it being a CI-generated select element. In CI, you create a select element like this:
$options = array(
'small' => 'Small Shirt',
'med' => 'Medium Shirt',
'large' => 'Large Shirt',
'xlarge' => 'Extra Large Shirt',
);
echo form_dropdown('shirts', $options);
If you'd like to create an extra option, simply tack it on to the end like so:
$options = array(
'small' => 'Small Shirt',
'med' => 'Medium Shirt',
'large' => 'Large Shirt',
'xlarge' => 'Extra Large Shirt',
'addother' => "Add other..."
);
echo form_dropdown('shirts', $options, null, 'id="myselect"');
Then, in your jQuery, test for $(this).val() == "addother" instead of "Add other...".
精彩评论