Friday, November 4, 2011

Custom JavaScript list - custom data elements

Custom JavaScript list Add / Remove elements.

Example: add / remove <li> element to <ul> list:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
<style type="text/css">
.list1 {}
.list1 li {list-style:none;}
</style>
</head>
<body>


<script type="text/javascript">

var ListManager = {
  
    next_position : 0,
    elems : [],
  
    add : function(_data) {
        this.elems[this.next_position] = _data;
        this.next_position++;
        this.addHTMLelement(this.next_position - 1);
        /* this.displayConsole(); */
    },
    remove : function(_pos) {
        /* this.elems.splice(_pos, 1); */
        var elems_new = [];
        for(var i in this.elems) {
            if(i != _pos) {
                elems_new[i] = this.elems[i];
            }
        }
        this.elems = elems_new;
        /* this.displayConsole(); */
    },
    displayConsole : function() {
        console.log('----------------');
        for(var i in this.elems) {
            console.log(i + ' : ' + this.elems[i].text + ', ' + this.elems[i].value);
        }
    },
  
    addHTMLelement : function(_pos) {
        var html = '';
        html += '<li id="list-element-'+_pos+'">';
        html += '<span style="cursor:pointer;color:red;" onclick="ListManager.remove(\''+_pos+'\');ListManager.removeHTMLelement(\''+_pos+'\');">x</span>';
        html += ' - ';
        html += this.elems[_pos].text;
        html += '</li>';
        $('#list1').append(html);
    },
  
    removeHTMLelement : function(_pos) {
        $('#list-element-'+_pos).css({display:'none'});
    }
  
}

function addElementToList(_value, _text) {
    ListManager.add({
        value : _value,
        text  : _text
    });
}

function randomRange(minVal, maxVal, floatVal) {
    var randVal = minVal+(Math.random()*(maxVal-minVal));
    return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

</script>


<input type="text" name="text1" id="text1" value=""/>
<input type="button" name="button1" value="add" onclick="addElementToList(randomRange(5, 15), $('#text1').val())"/>
<input type="button" name="button2" value="clear" onclick="$('#text1').val('');"/>

<ul id="list1" class="list1"></ul>


</body>
</html>


No comments: