Jacob J Jacob J - 17 days ago 5
CSS Question

Custom select dropdown, unable to select user added item

So I have this custom dropdown select that i'm building. It has some nested items in there and as the first option, the user can create their own item. I've got it working so they can click it, type in there, and once they hit enter it will be selected. The thing I can't figure out is after they have created it, and then they select something else, they are unable to go back to select that newly created item. Hopefully that makes sense. Here is the jsfiddle https://jsfiddle.net/johnsonjpj/18zm9kwz/2/

This is the part of the script i'm using to change that add button into an input, and then replace that data back into the list.

$(document).ready(function() {


$('body').on('click', '.addBtn', function(){

var $el = $(this).parent('.newInner');

var $input = $('<input type="text" class="form-control">');
$input.attr('placeholder', 'Enter your category name and press "Enter"');
// <span class="btn btn-default btn-xs"><i class="fa fa-check" aria-hidden="true"></i></span>
$el.replaceWith( $input );

var save = function(){
var $p = $('<span class="catName" />').text( $input.val() );
$input.replaceWith( $p );
$('.category-active').removeClass('category-active');
$('.addNew').removeClass('addNew').addClass('list-group-item category-active');
$('#categoryPlaceholder').attr('value', $input.val());


var container = $(".list-group.list-group-root");
container.hide();
$('.category-select').removeClass('category-open');

};

$input.one('blur', save).focus();

$input.keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
save();
}
});

});
});


All help is very much appreciated. Thanks!

Answer

When the document has loaded the first time you add the function $('.catName').on('click', function() {...} to all categories. This is the function that handles the selection and without it you can not click on any items, right?

The way you use on('click'...) is a so called direct-binding and only applies to current object.

So this function is applied to all existing items at that time. So when the user adds a new item to the list, this new item is missing this function and can therefore not be selected.

To fix this you need to add a delegated-binding instead which you do by changing

$('.catName').on('click', function() {

to

$('body').on('click','.catName', function() {
Comments