2017-03-13 110 views
1

我試圖創建一個用戶輸入計算方法,其中輸入字段和計算公式是動態設置的。例如,有一個蘋果數量一個蘋果價格投入,所以我乘以投入得到的價格。在另一種情況下,我有長度,寬度高度輸入來計算音量。將Alpacajs表單追加到現有表單

我決定存儲輸入,數據和計算功能並重新組裝形式形式JSON與Alpacajs

但是計算字段僅一個更大形式的一部分。 因此,使用

$("#alpacaForm").alpaca(window.alpacaForm.object); 

增加了alpacaForm元素中的新形式。

有沒有辦法可以將追加由alpacajs生成的字段到現有的表單?

回答

1

我設法做到這一點的唯一方法是通過渲染到一個單獨的元素和複製元素。

例如:

<form id="my-form"> 

    <!-- My controls: --> 
    <label for="foo">Foo</label> 
    <input id="foo"> 

    <label for="bar">Bar</label> 
    <input id="bar"> 

    <!-- I want the schema-based controls to go into this div. --> 
    <div class="schema-control-container"></div> 

</form> 

中的JavaScript(和jQuery):

var $myForm = $('#my-form'); 
var $schemaControlContainer = $myForm.find('.schema-control-container'); 
var mySchema = JSON.parse(mySchemaJson); 

var $scratchpad = $('<div id="alpacaScratchpad"></div>').hide(). 
    insertAfter($myForm); 

function postRender (control) { 

    // I actually have multiple forms, so I need to make sure the IDs are unique. 
    $scratchpad.find('.alpaca-control').each(function (i, alpacaControl) { 
    alpacaControl.id = $myForm.attr('id') + '-' + alpacaControl.id; 
    }); 
    $scratchpad.find('.alpaca-control-label').each(
     function (i, alpacaControlLabel) { 
    alpacaControlLabel.htmlFor = $myForm.attr('id') + '-' + 
     alpacaControlLabel.htmlFor; 
    }); 

    // Select elements we want to copy. Note that I haven't tried this with any 
    // particularly complicated JSON schemata, so this may be naïve. 
    var $goodies = $scratchpad.find('.alpaca-control,.alpaca-control-label'); 

    // Optional: mark schema controls as such, and allow autocompletion. 
    $goodies.filter('.alpaca-control').addClass('my-schema-datum'). 
     attr('autocomplete', null); 

    // Remove Alpaca classes and Bootstrap crap. (I hate Bootstrap, but the 'web' 
    // version of Alpaca doesn't seem to work right now. TODO: Update after 
    // https://github.com/gitana/alpaca/issues/507 is fixed.) 
    $goodies.removeClass('alpaca-control').removeClass('alpaca-control-label'). 
     removeClass('form-control').removeClass('control-label'); 

    // Move the goodies to the schema control container, in the form. 
    $schemaControlContainer.append($goodies); 

    // Clean up the clutter we don't need. 
    $scratchpad.empty(); 
} 

// Have Alpaca render the schema into the scratchpad, and then run the function 
// we just defined. 
$scratchpad.alpaca({ schema: mySchema, postRender: postRender }); 

我希望能找到一個羊駝選項,以防止需要做這一切,但似乎並不成爲一個。

相關問題