0

I have this code which was working earlier. Then I started putting the code into small small functions and now it is not working. I can see that it is adding list item but automatically removing it also. Please guide -

<body>
    <header>
            <h1>Your Ration List</h1>

    </header>
    <div id="container">
        <form class="shopList-form">
            <input id="add" type="text" placeholder="Type new item here" />
        </form>
        <ul id="item_list">
            <li id="base" class="hidden">
                <form>
                    <input class="check" type="checkbox" /> <span class="item">Item</span>

                </form>
                <button class="delete_item hidden"></button>
            </li>
        </ul>

JQuery code -

$(document).ready(function () {
    /* Get user input */
    getItem();

    function getItem() {
        $('input#add').keydown(function (event) {
            if (event.keyCode == 13) {
                addItem();
            }
        });
    }

    function addItem() {
        $('li#base').clone(true).appendTo('#item_list').removeAttr('id').removeClass('hidden');
        $('ul#item_list>li:last>form>span').text($('input#add').val());
        $('input#add').val("");
    }
});

Full code can be found at this JSFiddle -

http://jsfiddle.net/varunksaini/Zjxq5/8/

2 Answers 2

3

Since it is a form, pressing enter not only triggers your function but also submits the form (since there is no action it submits to itself) so the page actually refreshes and that is why the new <li> is gone.

All you need to do is add return false to getItem.

see fiddle: http://jsfiddle.net/Zjxq5/9/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, just realized that and removed the form as I don't need it.
1

The problem you have with your script is that you are using a form and when you press enter it submits the form to the server and reloads the page. You can use the preventDefault() function to avoid that.

$('input#add').keydown(function (event) {

        if (event.keyCode == 13) {
            event.preventDefault();
            addItem();
        }
});

Example: http://jsfiddle.net/rdnKq/1/

2 Comments

Thanks, just realized that and removed the form as I don't need it.
No need to remove the form if you don't want to ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.