Posted: February 28th, 2013 | Author: Christopher Vigliotti | Filed under: jQuery | No Comments »
I had a requirement pop up recently that had me fiddling with jqTree. I wanted to be able to add a new parent or sibling node to a tree. Thankfully the author of jqTree provided the addParentNode() and addNodeAfter() functions.
First I created a page that allowed me to add a new parent or sibling node to node id 1…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
| <html>
<head>
<title>jqTree Example 1: adding a new parent node and/or a sibling node to node id 1</title>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="scripts/tree.jquery.js"></script>
<link rel="stylesheet" href="jqtree.css">
<script>
$(document).ready(function() {
// get the data
var data = [
{
label: 'node1',
id: 1,
children: [
{
label: 'child1',
id: 2
},
{
label: 'child2',
id: 3
}
]
},
{
label: 'node2',
id: 4,
children: [
{
label: 'child3',
id: 5
}
]
}
];
// Create tree widget
$(function() {
$('#tree1').tree({
data: data,
autoOpen: true,
saveState: true
});
});
// add a listener for the addParent button
$("#addParent").click(function() {
// get the tree
var $tree = $('#tree1');
// get the node with id 1
var node = $tree.tree('getNodeById', 1);
// add a parent node to node id 1
$('#tree1').tree(
'addParentNode',
{
label: 'new parent added to node1',
id: 6
},
node
);
});
// add a listener for the addNodeAfter button
$("#addNodeAfter").click(function() {
// get the tree
var $tree = $('#tree1');
// get the node with id 1
var node = $tree.tree('getNodeById', 1);
// add a parent node to the node id 1
$('#tree1').tree(
'addNodeAfter',
{
label: 'new node added after node1',
id: 6
},
node
);
});
});
</script>
</head>
<body>
<input type="button" id="addParent" value="addParent" />
<input type="button" id="addNodeAfter" value="addNodeAfter" />
<div id="tree1"></div>
</body>
</html> |
Next I tweaked the code so that it created a new parent or sibling node for the last clicked node. The secret sauce here is to bind to tree.click so that I could store the last clicked node in a variable (for use in other functions).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
| <html>
<head>
<title>jqTree Example 2: adding a new parent node and/or a sibling node to the last node clicked</title>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="scripts/tree.jquery.js"></script>
<link rel="stylesheet" href="jqtree.css">
<script>
// any time a node is clicked we will store it in this variable (see below)
var clickedNode = null;
$(document).ready(function() {
// get the data
var data = [
{
label: 'node1',
id: 1,
children: [
{
label: 'child1',
id: 2
},
{
label: 'child2',
id: 3
}
]
},
{
label: 'node2',
id: 4,
children: [
{
label: 'child3',
id: 5
}
]
}
];
// Create tree widget
$(function() {
$('#tree1').tree({
data: data,
autoOpen: true,
saveState: true
});
});
// add a listener for the addParent button
$("#addParent").click(function() {
// if at least one node has been clicked
if(clickedNode != null){
// add a new parent to the clicked node
$('#tree1').tree(
'addParentNode',
{
label: 'new parent added to node1',
id: 6
},
clickedNode
);
}
});
// add a listener for the addNodeAfter button
$("#addNodeAfter").click(function() {
// if at least one node has been clicked
if(clickedNode != null){
// add a new node after the clicked node
$('#tree1').tree(
'addNodeAfter',
{
label: 'new node added after node1',
id: 6
},
clickedNode
);
}
});
// bind the 'tree.click' event (fires each time the tree is clicked)
$('#tree1').bind(
'tree.click',
function(event) {
// write the clicked node to the variable, for use
// in the addParent and addNodeAfter listeners above
clickedNode = event.node;
}
);
});
</script>
</head>
<body>
<input type="button" id="addParent" value="add parent to selected item" />
<input type="button" id="addNodeAfter" value="add node after selected item" />
<div id="tree1"></div>
</body>
</html> |
Until next time, fellow code monkeys!
Posted: March 13th, 2012 | Author: Christopher Vigliotti | Filed under: JavaScript, jQuery | 2 Comments »
I’ve been doing a lot of Javascript / jQuery work over the last week and have been using Firebug’s handy-dandy console.log() debugging method. Thanks to the awesomeness that is Firebug the era of debugging one’s JavaScript code with irritating alert() messages is over. One gotcha that I’ve fallen for more than once this past week is that leaving console.log() calls in your code when you aren’t running Firebug will cause JavaScript errors. A simple work-around for this problem is to have JavaScript test for the existence of console before attempting to log the message. I’m doing this in the code sample below in a function that I’ve named consoleLog().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
function booya(){
// this will make IE cry like a sad, sad baby when Firebug is not present
console.log('booya');
// this will appease the demon child
consoleLog('method booya() in the house');
}
function consoleLog(message){
if(window.console){
console.log(message);
}
} |
Ideally one should not be leaving debug code in their completed work, but I make an exception in cases where the debugging code serves as a code comment that may be helpful to other developers.
You can read more about Firebug and Logging here.
Posted: March 6th, 2012 | Author: Christopher Vigliotti | Filed under: JavaScript, jQuery | No Comments »
Here’s a bit of code that calculates the sum of the values found in a group of form fields. Dollar signs, decimals and commas are added to each form field as-needed, non-numeric characters are brought to the user’s attention. I chose not to leverage the jQuery Calculation Plug-in because I wanted small/light code that targeted the following requirements:
- calculate the sum of a group of form fields
- add dollar signs, decimals and commas as-needed
- ignore non-numeric form field values during calculation, but alert the user
You can check out a working example here and check out the code below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
| <script>
jQuery(document).ready(function(){
// call doTotals() once when the page loads
doTotals('calc','total','error_');
doTotals('morecalc','anothertotal','error_');
// call doTotals() each time one of the 'calc' fields or 'morecalc' fields change
jQuery('.calc').change(function(){
doTotals('calc', 'total','error_');
});
jQuery('.morecalc').change(function(){
doTotals('morecalc','anothertotal','error_');
});
});
// spiffy function that adds commas to a number
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
/*
this function...
1. adds a group of form fields
2. formats the form fields
3. writes the total
4. highlights any errors
usage...
doTotals('calc','total','error_');
where
'calc' is a the class name that is present in each form field that you want to add
and
'total' is the id of the span/div that you wish to display the total in
and
'error_'
is the name of the span that accompanies each form field. an error message will be displayed in this span
*/
function doTotals(valuesClassName, totalIdName, errorIdPrefix){
var doWriteDollarSignsToFormFields = true;
var total = 0;
jQuery('.' + valuesClassName).each(function(){
value = jQuery(this).val();
// remove all whitespace
while(value.indexOf(' ') != -1){
value = value.replace(' ', '');
}
// remove all dollar signs
while(value.indexOf('$') != -1){
value = value.replace('$', '');
}
// remove all commas
while(value.indexOf(',') != -1){
value = value.replace(',', '');
}
// if at this point value is blank, change it to 0
if(value == ''){
value = '0';
}
// if at this point the value is not blank and is a number...
errorFieldName = '#' + errorIdPrefix + jQuery(this).attr('id');
if(value != '' && ! isNaN(value)){
// write the cleaned value (with commas) to the form field
if(doWriteDollarSignsToFormFields == true){
jQuery(this).val('$' + addCommas(parseFloat(value).toFixed(2)));
}else{
jQuery(this).val(addCommas(parseFloat(value).toFixed(2)));
}
// convert the value and add it to the total
valueParsed = parseFloat(value);
total = total + valueParsed;
// console.log('remove error from span id ' + errorFieldName);
jQuery(errorFieldName).html("");
}else{
// console.log('write error to span id ' + errorFieldName);
jQuery(errorFieldName).html("<< please enter a numeric value");
}
});
// update the total
if(doWriteDollarSignsToFormFields == true){
jQuery('#' + totalIdName).html('$' + addCommas(parseFloat(total).toFixed(2)));
}else{
jQuery('#' + totalIdName).html(addCommas(parseFloat(total).toFixed(2)));
}
}
</script> |
…and here’s an HTML table…
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
| <h1>add em' up!</h1>
<table style="width:800px;">
<tr>
<td style="width:400px;vertical-align:top;">
<h2>group a</h2>
<input type="text" class="calc" id="calc1" value="$55.50" />
<span id="error_calc1">error_calc1</span><br />
<input type="text" class="calc" id="calc2" value="19.99" />
<span id="error_calc2">error_calc2</span><br />
<input type="text" class="calc" id="calc3" value="" />
<span id="error_calc3">error_calc3</span><br />
<input type="text" class="calc" id="calc4" value="" />
<span id="error_calc4">error_calc4</span><br />
<input type="text" class="calc" id="calc5" value="cheese" />
<span id="error_calc5">error_calc5</span><br />
</td>
<td style="width:400px;vertical-align:top;">
<h2>group b</h2>
<input type="text" class="morecalc" id="calc6" value="" />
<span id="error_calc6">error_calc6</span><br />
<input type="text" class="morecalc" id="calc7" value="" />
<span id="error_calc7">error_calc7</span><br />
<input type="text" class="morecalc" id="calc8" value="" />
<span id="error_calc8">error_calc8</span><br />
</td>
</tr>
<tr>
<td>
<h2>total a</h2>
<span id="total">0.00</span>
</td>
<td>
<h2>total b</h2>
<span id="anothertotal">0.00</span>
</td>
</tr>
</table> |
The power of jQuery compels me!
Posted: August 18th, 2011 | Author: Christopher Vigliotti | Filed under: ColdFusion, jQuery | 1 Comment »
Most ColdFusion developers are using either ColdFusion Builder or Eclipse (with added CFEclipse awesomeness). I’m presently using CFEclipse for ColdFusion development, but when I have to create HTML prototypes I use Adobe Dreamweaver. This morning I leveraged Dreamweaver’s templates and jQuery code completion features to get an ajax-powered, interactive prototype up and running in an hour.
I’m wondering why the folks at Adobe didn’t just add some of ColdFusion Builder’s awesome features to Dreamweaver.
Posted: September 3rd, 2010 | Author: Christopher Vigliotti | Filed under: AJAX, JavaScript, jQuery | No Comments »
I am the process of migrating a code base from Prototype + old-school JS to jQuery (the new mayor of Awesome Town), and ran across some code that was replacing some (but not all) styles of an element. This led me to jQuery’s css() method, one of the many handy CSS-related features in jQuery.. As I often do when tinkering with a new language, library, framework or feature I like to whip up a code sample. With this example I was able to see that the css() method adds css to an element without replacing other css attributes. A working example can be found here.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| <html>
<head>
<title>styles</title>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function modColor(){
jQuery("#awesometown").css
({
'color':'red'
});
}
function modStyle(){
jQuery("#awesometown").css
({
'text-decoration':'underline'
});
}
function modVis(){
jQuery("#awesometown").css
({
'display':'none'
});
}
function modSize(){
jQuery("#awesometown").css
({
'color':'black',
'text-decoration':'none',
'display':''
});
}
</script>
</head>
<body>
<h1 id="awesometown">I Am An H1 Tag On A Page With No Meaningful Content</h1>
<em>sung to the tune of "Horse With No Name"</em>
<hr />
<a href="javascript:modColor();">red,</a>
<a href="javascript:modStyle();">underlined,</a>
<a href="javascript:modVis();">gone,</a>
<a href="javascript:modSize();">reset</a>
</body>
</html> |
UPDATE
Here is another code snippet. This replaces five lines of code with one.
1
2
3
4
5
6
7
8
9
| // the old code
$('XYZ').select('table.thisIsAClassname').each(
function (e) {
e.style.display = 'none';
}
);
// the new code
jQuery(".thisIsAClassname").css("display", "none"); |
Posted: June 30th, 2010 | Author: Christopher Vigliotti | Filed under: JavaScript, jQuery | No Comments »
I’ve been reading a lot about jQuery these days. First my friend and former associate Rick “American” Flagg suggested that I check it out, then I took notice of Ray Camden’s recent posts on jQuery. With the power of suggestion now firmly behind the wheel I headed over to the jQuery website, and worked through the first few tutorials.
Now I fancy myself a bit of a JavaScript hack, so after coding the examples in the first two lessons I began to tinker a bit. I ended up with the following fun and pointless bit of code…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
| <!--- what exactly is a "google a pis"? --->
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
// old-school JS stuff
// declare your variables!
var columnIdsList = "";
var columnIds = new Array();
var beginRedraw = false;
var i = -1;
var theIntervalId = 0;
// redraw the table cells
function redrawStuff(){
i = i + 1;
theIntervalId = setInterval("hiThere()", 50);
$("body").removeClass("whiteBkg");
$("body").addClass("blackBkg");
}
function hiThere() {
//
// alert(columnIds.length);
if(i < columnIds.length){
document.getElementById(columnIds[i]).className="blackTd";
clearInterval(theIntervalId);
redrawStuff();
}else{
clearInterval(theIntervalId);
beginRedraw = false;
columnIds = new Array();
// alert(columnIds.length);
i = -1;
$("body").removeClass("blackBkg");
$("body").addClass("whiteBkg");
}
}
// jQuery stuff
$(document).ready(function(){
// when you hover over a TD
$("td").hover(function() {
columnIdsList = columnIds.toString();
if(beginRedraw == false){
if(columnIds.length > 15){
beginRedraw = true;
redrawStuff();
}else{
$(this).removeClass("blackTd");
$(this).removeClass("orangeTd");
$(this).addClass("whiteTd");
// add the columnId to the array
if(columnIdsList.search(this.id) == -1){
columnIds.push(this.id);
}
}
}
},function(){
if(beginRedraw == false){
$(this).removeClass("whiteTd");
$(this).addClass("orangeTd");
}
});
});
</script>
<style type="text/css">
.blackBkg {
background-color: #000000;
}
.whiteBkg {
background-color: #FFFFFF;
}
.blackTd {
background-color: #000000;
height: 40px;
width: 40px;
text-align:center;
}
.whiteTd{
background-color: #FFFFFF;
height: 40px;
width: 40px;
text-align:center;
}
.orangeTd{
background-color: ORANGE;
height: 40px;
width: 40px;
text-align: center;
}
</style>
<table>
<cfoutput>
<cfloop from="1" to="6" index="variables.rowIndex" step="1">
<tr>
<cfloop from="1" to="6" index="variables.columnIndex" step="1">
<td
class="blackTd"
id="r#variables.rowIndex#c#variables.columnIndex#"
>r#variables.rowIndex#c#variables.columnIndex#</td>
</cfloop>
</tr>
</cfloop>
</cfoutput>
</table> |
I look forward to continuing to use jQuery a bit more…perhaps to make something useful