-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjquery.addremovetextbox.js
318 lines (248 loc) · 11.6 KB
/
jquery.addremovetextbox.js
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*
* AddRemoveTextbox v1.2.1
* https://www.github.com/kloverde/jquery-AddRemoveTextbox
*
* Donations: https://paypal.me/KurtisLoVerde/5
*
* Copyright (c) 2016, Kurtis LoVerde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function( $ ) {
"use strict";
$.fn.addRemoveTextbox = function( options ) {
var settings = $.extend( {
// A CSS class to style the 'Add' button. The generated HTML will be a <span>, so it is
// assumed that you will use CSS to define a background image.
addButtonClass : "addButton",
// Hover text for the 'Add' button
addButtonTooltip : null,
// A CSS class to style the 'Remove' button. The generated HTML will be a <span>, so it is
// assumed that you will use CSS to define a background image.
removeButtonClass : "removeButton",
// Hover text for the 'Remove' button
removeButtonTooltip : null,
// A limit on the number of fields which may exist under the applicable ID prefix. Default
// is null (no limit). If a value is specified, it must be an integer greater than 1.
maxFields : null,
// If true, renumber the id and name attributes upon initialization and when a row is removed.
// Renumbering is based on DOM order, not `id` or `name` values, and starts on the value
// specified by `startingNumber`. This setting is disabled by default because it can break
// applications. Be sure that your application can handle changing IDs and names before using this.
contiguous : false,
// This setting is used only when 'contiguous' is set to true.
startingNumber : 0,
// A callback function for add operations. Your callback must accept two string arguments:
// arg1: the id attribute of the added row
// arg2: the name attribute of the added row
addCallback : null,
// A callback function for remove operations. Your callback must accept three string arguments:
// arg1: the id attribute of the removed row
// arg2: the name attribute of the removed row
// arg3: the value of the removed row
removeCallback : null
}, options );
if( this.length === 0 || this == null ) {
throwException( "No matching field(s) found" );
}
var ID_PREFIX = this.attr( "id" ).replace( /\[?[0-9]*\]?$/, "" );
var IS_NUMBERED_NOTATION = this.attr( "id" ).match( /[0-9]+$/ ) != null;
var IS_ARRAY_NOTATION = this.attr( "id" ).match( /\[[0-9]\]$/ ) != null;
if( !IS_NUMBERED_NOTATION && !IS_ARRAY_NOTATION ) {
throwException( "Invalid ID attribute '" + this.attr("id") + "': IDs must be nunmbered like id1, id2, or use array notation, like id[0], id[1]" );
} else if( IS_NUMBERED_NOTATION && IS_ARRAY_NOTATION ) {
throwException( "Invalid state: ID '" + this.attr("id") + "' notation not detected correctly" ); // should be impossible
}
if( settings.maxFields != null ) {
var errMsg = "maxFields (" + settings.maxFields + ") must be an integer greater than 1";
if( isNaN(settings.maxFields) ) {
throwException( errMsg );
} else {
if( settings.maxFields < 2 || settings.maxFields % 1 !== 0 ) {
throwException( errMsg );
}
settings.maxFields = parseInt( settings.maxFields );
}
}
if( settings.contiguous === true ) {
if( settings.startingNumber != null ) {
var errMsg = "startingNumber (" + settings.startingNumber + ") must be an integer greater than or equal to 0";
if( isNaN(settings.startingNumber) ) {
throwException( errMsg );
} else {
if( settings.startingNumber < 0 || settings.startingNumber % 1 !== 0 ) {
throwException( errMsg );
}
settings.startingNumber = parseInt( settings.startingNumber );
}
}
}
init( this );
function throwException( msg ) {
throw "AddRemoveTextbox error: " + msg;
}
function init( invokedBox ) {
var fields = $( "input[id^='" + ID_PREFIX + "']" );
if( settings.maxFields != null && fields.length > settings.maxFields ) {
throwException( "There are more fields in the '" + ID_PREFIX + "' set (" + fields.length +
") than are allowed by maxFields (" + settings.maxFields + ")" );
}
fields.each( function() {
var inputField = $( this );
var parentRow = inputField.parent();
makeRemoveButton().insertAfter( inputField );
if( parentRow.is(":last-child") ) {
makeAddButton().appendTo( parentRow );
}
} );
rebuild();
}
function makeButton( className, title ) {
var btn = $( "<span></span>" );
if( className != null ) {
btn.addClass( className );
}
if( title != null ) {
btn.attr( "title", title );
}
return btn;
}
function makeAddButton() {
var btn = makeButton( settings.addButtonClass, settings.addButtonTooltip );
btn.on( "click", function() {
var newInputId = insertRow( $(this) );
$( escape("#" + newInputId) ).focus();
} );
return btn;
}
function makeRemoveButton() {
var btn = makeButton( settings.removeButtonClass, settings.removeButtonTooltip );
btn.on( "click", function() {
removeRow( $(this) );
} );
return btn;
}
function domScan() {
var highestNumberedBox = null;
var physicallyLastBox = null;
var boxes = $( "input[id^='" + ID_PREFIX + "']" );
boxes.each( function() {
var jqThis = $( this );
if( highestNumberedBox == null ) highestNumberedBox = jqThis;
physicallyLastBox = jqThis;
if( highestNumberedBox.attr("id") > jqThis.attr("id") ) {
return;
}
highestNumberedBox = jqThis;
} );
return {
highestBox : highestNumberedBox,
lastBox : physicallyLastBox,
numBoxes : boxes.length
};
}
function insertRow( button ) {
var lastRow = button.parent();
var newRow = lastRow.clone( true ); // Passing 'true' so that the button click events are cloned
var newInput = newRow.children( "input" );
var nextIdResults = getNextId();
newInput.val( "" );
newInput.attr( "id", nextIdResults.nextId );
newInput.attr( "name", newInput.attr("id") );
button.remove();
if( settings.maxFields != null && nextIdResults.numBoxes + 1 >= settings.maxFields ) {
newRow.find( "span[class='" + settings.addButtonClass + "']" ).remove();
}
newRow.insertAfter( lastRow );
if( typeof settings.addCallback === "function" ) {
settings.addCallback( nextIdResults.nextId, nextIdResults.nextId );
}
return nextIdResults.nextId;
}
function getNextId() {
var domScanResults = domScan();
if( settings.maxFields != null && domScanResults.numBoxes >= settings.maxFields ) {
throwException( "Field count limit reached for " + ID_PREFIX );
}
var highestBox = domScanResults.highestBox;
var highestNum = parseInt( highestBox.attr("id").replace(/.*(\d+).*$/, "$1") );
var nextNum = highestNum + 1;
var nextId = IS_ARRAY_NOTATION ? ID_PREFIX + "[" + nextNum + "]"
: ID_PREFIX + nextNum;
return {
nextId : nextId,
numBoxes : domScanResults.numBoxes
};
}
function removeRow( button ) {
var rowToRemove = button.parent();
var prevRow = rowToRemove.prev();
var inputToRemove = rowToRemove.children( "input" );
var inputToRemoveVal = inputToRemove.val();
var inputId = inputToRemove.attr( "id" );
var inputName = inputToRemove.attr( "name" );
// Don't remove the row if it's the only/last one in the group.
var othersExist = false;
$( "input[id^='" + ID_PREFIX + "']" ).each( function() {
if( $(this).attr("id") !== inputId ) {
othersExist = true;
return;
}
} );
if( othersExist ) {
if( rowToRemove.is(":last-child") ) {
makeAddButton().appendTo( prevRow );
} else {
if( !rowToRemove.parent().last().find("span[class='" + settings.addButtonClass + "']").length ) {
makeAddButton().appendTo( rowToRemove.siblings(":last") );
}
}
rowToRemove.remove();
rebuild();
} else {
inputToRemove.val( "" );
}
if( typeof settings.removeCallback === "function" ) {
settings.removeCallback( inputId, inputName, inputToRemoveVal );
}
}
function rebuild() {
if( settings.contiguous === true ) {
var currNum = settings.startingNumber;
$( "input[id^=" + ID_PREFIX + "]" ).each( function() {
var field = $(this);
var newId = IS_ARRAY_NOTATION ? ID_PREFIX + "[" + currNum + "]"
: ID_PREFIX + currNum;
field.attr( "id", newId );
field.attr( "name", newId );
currNum++;
} );
}
}
function escape( selector ) {
return selector.replace( /(\[|\])/g, "\\$1" );
}
};
}( jQuery ));