Reputation: 319
I've done the create function (demo here ), but now having some trouble implementing the edit part. The edit code is working alone perfectly here, just tht I don't know how to combine them to work together..
current code : html
<ul style="list-style:none;margin:0;padding:0">
<li style="list-style:none" id="active" ><a href="#" >Personal</a></li>
<li><a href="#" id="add">Add</a></li>
</ul>
<input type="text" name="task-group" style="display:none">
jquery
$(document).ready(function(){
$("input[name=task-group]").hide();
var addBtn = $("#add");
var inputBar = $("input[name=task-group]");
$(addBtn).click(function(){
$(this).hide();
$(inputBar).show().focus();
$(inputBar).val('');
});
$(inputBar).blur(function(){
if($(inputBar).val() !== ""){
var text = $(this).val();
$(addBtn).show();
$(inputBar).hide();
$('#active').append("<li id='active'><a href='#'>" + text + "</a></li>");
} // if close
else {
$(addBtn).show();
$(inputBar).hide();
}
});
$(inputBar).keydown(function (e){
if(e.keyCode == 13){
$(this).blur();
}
});
});
Upvotes: 1
Views: 247
Reputation: 1714
Look at jsfiddle
Change your html as:
<ul class="container" style="list-style:none;margin:0;padding:0">
<li style="list-style:none" class="item" id="active" ><a href="#" >Personal</a></li>
</ul>
<br/>
<a href="#" id="add">Add</a>
<input type="text" name="task-group" style="display:none"/>
Change your javascript as:
$(document).ready(function () {
$("input[name=task-group]").hide();
var addBtn = $("#add");
var inputBar = $("input[name=task-group]");
var beforeItems = $('li.item');
$(addBtn).click(function () {
$(this).hide();
$(inputBar).show().focus();
$(inputBar).val('');
});
$(inputBar).blur(function () {
if ($(inputBar).val() !== "") {
var text = $(this).val();
$(addBtn).show();
$(inputBar).hide();
$('ul.container').append("<li class='item' ><a href='#'>" + text + "</a></li>");
items = $('li.item');
items.on('click', itemClick);
} // if close
else {
$(addBtn).show();
$(inputBar).hide();
}
});
$(inputBar).keydown(function (e) {
if (e.keyCode == 13) {
$(this).blur();
}
});
var itemClick = function (e) {
var $this = $(e.target).closest('li.item');
var txt = $this.find('a').text();
var activeInput = $("<input type='text'/>").val(txt);
$this.html('');
activeInput.appendTo($this).focus();
activeInput.on('blur', activeInputBlur);
};
var activeInputBlur = function (e) {
var $this = $(e.target);
var v = $this.val();
if (v.trim() == "") {
alert('Field cannot be empty');
$this.focus();
} else {
var $a = $("<a href='#'>" + v + "</a>");
$this.parent().append($a);
$this.remove();
}
};
beforeItems.on('click', itemClick);
});
Upvotes: 2