jQuery append, prepend and remove

Posted By: Ian on Nov 10, 2013 in JQuery
Last modified on January 29th, 2015 at 9:31 pm,

Simple job list using the jQuery append, prepend and remove methods

For the purpose of this demo i describe the methods in how they are used for the job list.

append – add new job to the end of the list.
prepend – add new job to the beginning of the list.
remove – remove the job

<script type="text/javascript">
    /**
     * Wait until DOM has loaded
     */
    $(document).ready(function () {
        /**
         * Bind click handler to our append and prepend buttons and call our function
         * passing the argument append or prepend depening on button clicked
         */
        $('#btnAppend').click(function () {
            addEntry('append');
        });
        $('#btnPrepend').click(function () {
            addEntry('prepend');
        });
    });
    /**
     * Declare our function and argument as a variable
     */
    function addEntry(where) {
        /**
         * Declare our variables
         */
        var newEntry = $('#txtNewEntry').val();
        var list = $('ol');
        var html = '<li>' + newEntry + ' <a href="#">remove</a></li>';
        /**
         * If where (variable) equals append append else prepend
         */
        if (where == "append") {
            list.append($(html));
        } else {
            list.prepend($(html));
        }
    };
    /**
     * Bind click handler to all a tags in #jobList
     * and onclick remove the selected li and return false to avoid
     * trying to follow link
     */
    $(function () {
        $('#jobList').on('click', 'a', function () {
            $(this).parent('li').remove();
            return false;
        });
    });
</script>

 

Demo

AnonymousIan.J.Gough

Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,
Ian.J.Gough

protected by copyscape duplicate content check

Categories


Powered by Banner Bar 125