Creating dynamic formula

后端 未结 3 722
自闭症患者
自闭症患者 2020-12-30 05:19

I need to create a ui that user will build up a formula. ie:

For one item formula is:

Cost * item / 100

For another item:

Item* 5 / 100

3条回答
  •  囚心锁ツ
    2020-12-30 05:50

    Check this fiddle you can improve the formula like you want

    html

    Insert your formula

    css

    body{font-family:arial,sans-serif;text-align:center}
    input{padding:6px;border:1p solid #999;margin:10px auto}
    

    js

    $('form').on('submit',function(e){
        e.preventDefault();
        $(this).hide();
        $('body').append($('
    ').hide().fadeIn(800)); var labDiv=$('div:first'); var varNames = []; var formula=$('input').val().toString(); var varStr=formula.replace(/[^a-zA-Z]+/g, ""); $.each(varStr.split(''), function(i, el) { if ($.inArray(el, varNames) === -1){ varNames.push(el); labDiv.append('
    '); } }); labDiv.prepend('

    '+formula+'

    '); labDiv.append('') $('#calculate').on('click',function(e){ e.preventDefault(); var result=formula.replace(/\(/g,'*(').replace(RegExp(':','g'),'/'); for(var ct=0;ct'+result.replace(/\*\(/g,'(')+'= '+eval(result.replace(',','.'))+''); }); $('#newFormula').one('click',function(e){ e.preventDefault(); labDiv.remove(); $('form#ula input:first').val(''); $('form#ula').fadeIn(); }); })

提交回复
热议问题