Skip to content

Instantly share code, notes, and snippets.

@mightybyte
Created January 3, 2011 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mightybyte/763184 to your computer and use it in GitHub Desktop.
Save mightybyte/763184 to your computer and use it in GitHub Desktop.
Javascript for digestive-functors massInput
inputHidden = flip inputRead "Error reading hidden" $ \id' inp ->
createFormHtml $ \cfg -> applyClasses' [htmlInputClasses] cfg $
H.input ! A.type_ "hidden"
! A.name (H.stringValue $ show id')
! A.id (H.stringValue $ show id')
! A.value (H.stringValue $ fromMaybe "" inp)
massInputHtml s d = mapView (fmap addControls) $ massInput inputHidden s d
where
addControls form = do
H.div ! A.class_ "massInput" $ do
H.div $ do
H.input ! A.type_ "button"
! A.onclick "addItem(this); return false;"
! A.value "Add Item"
H.input ! A.type_ "button"
! A.onclick "removeItem(this); return false;"
! A.value "Remove Item"
form
function findMassInput(button) {
var mainDiv = $(button).parent();
while ( !mainDiv.hasClass('massInput') ) {
mainDiv = $(mainDiv).parent();
}
return mainDiv;
}
function findItems(button) {
return $('.massInputItem', findMassInput(button));
}
function addItem(button) {
var count = $(':hidden', findMassInput(button))[0];
var items = findItems(button);
var item = $(items[items.length-1]);
var newItem = item.clone(true);
var i;
// Increment counter
$(count).val(parseInt($(count).val())+1);
// We have to change the raw html because IE doesn't allow the
// name field to be changed.
newItem.html(newItem.html().replace(/fval\[(\d+\.)*(\d+)\.(\d+)\]/g,
function(a, b, c, d) {
var newC = parseInt(c)+1;
return a.replace(/\d+\.\d+\]/, newC+'.'+d+']');
}
));
newItem.appendTo(item.parent());
// Copy the values of all children that had the name attribute set.
// The direct html insertion does not preserve the most current
// values. It only preserves default values, so if we want values
// copied, we have to use an approach like this.
var items2 = findItems(button);
var newLast = $(items2[items2.length-1]);
var c1 = $('[name]', item);
var c2 = $('[name]', newLast);
if ( c1.length == c2.length ) {
for ( i = 0; i < c1.length; i++ ) {
$(c2[i]).val($(c1[i]).val());
}
}
}
function removeItem(button) {
var items = findItems(button);
if ( items.length > 1 ) {
var count = $(':hidden', findMassInput(button))[0];
var item = $(items[items.length-1]);
item.remove();
// Decrement counter
$(count).val(parseInt($(count).val())-1);
} else {
alert('Cannot remove any more rows');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment