JQuery Create new LI tag in existing Bootstrap dropdown
I want to create a new item and it should add this item to the existing bootstrap dropdown using jQuery. The dropdown should also automatically select the new item. <li>
(<ul>)
Can someone please help me?
Thanks in advance!
HTML:
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
Select Items <span class="caret"></span>
</button>
<ul class="dropdown-menu reddy" role="menu">
<li><input type="text" class="form-control"><button type="button" class="btn btn-primary btn-xs">Create New</button></li>
<li><a href="#"><label for="menuitem1"><input type="checkbox" id="menuitem1" /> Menu Item 1</label></a></li>
<li><a href="#"><label for="menuitem2"><input type="checkbox" id="menuitem2" /> Menu Item 2</label></a></li>
<li><a href="#"><label for="menuitem3"><input type="checkbox" id="menuitem3" /> Menu Item 3</label></a></li>
</ul>
</div>
CSS
.form-control{max-width:140px;float:left;margin-right:5px;margin-left:10px;}
.btn{margin-top:5px;}
.open>.dropdown-menu{width:250px;}
Please find Preview in Fiddle here
source to share
You can add HTML using the method append()
. To "auto" check a new checkbox in a new menu item, simply set the attribute checked
to "checked"
$("#createnew").on("click", function() {
var $dropdown = $(".dropdown-menu.reddy");
var menuItemNo = $dropdown.find("li").length;
var menuItemId = "menuitem" + menuItemNo;
$dropdown.append("<li><a href='#'><label for='" + menuItemId + "'><input type='checkbox' id='" + menuItemId + "' checked='checked' /> Menu Item " + menuItemNo +"</label></a></li>");
});
See updated example here: http://jsfiddle.net/br98nxj9/1/
source to share
Just updated it a little. Check out this fiddle http://jsfiddle.net/pamxnouh/
This is the javascript that is being used. Make sure your create button has the id "new-li".
$('#new-li').on('click', function(event){
event.stopPropagation();
var x = $(event.target).closest('ul').find("a").size()+1;
$(event.target).closest('ul').append("<li><a href='#'><label for='menuitem"+x+"'><input type='checkbox' id='menuitem"+x+"' />"+$(event.target).siblings('input').first().val()+"</label></a></li>");
$(event.target).closest('ul').find('input').each(function(){
$(this).prop('checked', false);
});
$(event.target).closest('ul').find('input').last().prop('checked', true);
});
source to share