Rahul Desai
Rahul Desai

Reputation: 15501

jQuery fetching incorrect data

In my todo app project here, I am having a problem.

Reproducing the problem: Add an unstarred item eg: x, now if you star/unstar this item, it will be updated in the localStorage. Now, edit this item to, eg: xxx, and now if you star/unstar this item, it does not update the localStorage. The reason is, the item text read is xxxxxx and NOT xxx. I checked it in console.log().

Why is this happening? What am I doing wrong here?

jsFiddle

Code:

function toggleStar(element, pushToUndoStack){
    console.log($(element).parent().find('p').text());
    // fetch this starred item content to locate it in the localStorage
    var starred_item = $(element).parent().find('p').text();

    // fetch current items from localStorage
    var todo_items = getLocalStorageData();

    // parse to locate 'that' item
    $.each(todo_items,function(index,item){
        //console.log(item[0]);
        if(starred_item.toLowerCase() === item[0].toLowerCase()){
            //console.log("found -> " + item[0]);
            // toggle starred true/false
            item[1] = !item[1];
            //console.log(item[1]);
            // cut the loop
            return false;
        }
    });

    // update localStorage                
    localStorage.setItem('todo_items', JSON.stringify(todo_items));

    if(pushToUndoStack){
        // update undo stack
        todo_item.undoStack.push(['toggleStar',$(element).parent().find('button').text(),$(element).parent().find('.star').prop('checked')]);
        $("#undo").removeAttr('disabled');
        //console.log(todo_item.undoStack);
    }
}

Upvotes: 0

Views: 55

Answers (1)

In your JS code you have function editItem(element, pushToUndoStack) with the code:

// replace textarea with the new text
$(element).find('textarea').replaceWith("<p class='item_content'>"+edited_text+"</p>");

Each time you edit your task you duplicate <p class='item_content'></p>. Change it with

// replace textarea with the new text
$(element).find('textarea').replaceWith(edited_text);

http://jsfiddle.net/G288G/1/

Upvotes: 2

Related Questions