Reputation: 21
I am a win32 amateur coder and a newbie web programmer. For my personal project I am trying to modify a to-do list code in codepen.
http://codepen.io/arjancodes/pen/Bahkb
Here is my code:
// get rid of default value in input box
$('input[name=toDoItem]').focus(function() {
$(this).val('');
})
$('#add').click(function() {
var $input = $('input[name=toDoItem]').val();
if ($input.length > 0) {
$('#list').append('<li class=' + 'close' + '>' + $input + '</li>');
} else {
alert("We'd all love to do nothing.");
}
// reset input box to no text
$('input[name=toDoItem]').val('');
});
// remove list item
$('#list').on('click', '.close', function() {
$(this).hide('2000', function() {
$(this).remove();
});
});
In this to do list project, when clicking on "x" button, it deletes the row. But when I click to text, it also deletes. What I am going to do, is to separate delete button and text. User will write a link to input box and add it to list. After that user will click to text and the page will redirect to the link. I am hoping someone can show me the right direction, I am not asking to write all the code for me!
Upvotes: 2
Views: 81
Reputation: 9093
Here's a start: codepen.
If you want to have the delete button and text separated, they should be separate elements. For example:
<li class='item'>Do Stuff <i class='close'></i></li>
The CSS is updated to float the <i>
to the right, and apply the :after
button styling to it.
The JS is updated to match the .close
and remove the parent/ancestor .item
:
$('#list .item .close').on('click', function() { ... ; return false; } );
The return false
is there so that clicking the .close
does not 'bubble' the event and invoke this new handler on the .item
:
$('#list').on('click', '.item', redirect_function);
The redirect_function
is not a closure, because it's re-used in the #add
event handler:
$('#list').append("<li class='item'>" + $input + "<i class='close'></i></li>")
As for redirecting to another URL, you can manipulate window.location
. But, since the Todo List is purely client side, changes are not persisted.
If you want to store the TODO lists on a server, you would have to communicate the changes to the server. Classically this is done using something like:
<form method='post'>
<ul>
<li><input type='text' name='item[]' value='Stuff to do'/></li>
<li><input type='text' name='item[]' value='....'/></li>
</ul>
<button type='submit' name='action' value='save-todo-list'>Save</button>
</form>
On the server-side, you would have a script that removes all todo list items for the authenticated user from a database, and insert the POST
ed items.
Alternatively, you can use AJAX. For instance, the 'delete item' handler could be
$('#list').on('click', '.item .close', function() {
$.ajax( {
method: 'POST',
url: "/api/todo/item/delete",
data: ...
}
} );
There's lots of resources on the matter.
Upvotes: 1
Reputation: 2290
You should use a structure like this:
<li>
ToDo text
<div class="close"><div>
</li>
Upvotes: 0