douhui8454 2013-12-15 01:12
浏览 51
已采纳

JQuery / JavaScript:遍历表单字段,执行计算,然后提交

Right now my code is very "hard-coded" and repetitive. I'd like to know if there is a cleaner way to do the following. Ideally, I want to iterate through my forms fields with a loop and calculate the results with one statement, but I'm struggling to figure out how best to do so.

Summary: I have ten form fields, each with a distinct decimal value that a user may or may not supply. When the user hits submit, it should add the value in the input field with a value being displayed on the current HTML page, then insert into the DB.

First, I grab that value from the form input field and convert it into a number with two decimal places. I then grab the current total from the HTML and add the two numbers together. After that I inject that total back into the form input field so that it can be stored in $_POST and inserted into a database.

How can I make my code more DRY (ie, Don't Repeat Yourself)? Below are just two examples but they are exactly the same except for the element calls:

var subtotal = Number($("#housing").val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-housing').html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#housing').val(total);

var subtotal = Number($("#utilities").val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-utilities').html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#utilities').val(total);

I would like to iterate through my input fields like so, but I'm trying to figure out how I could display the logic inside:

var input = $('.form-expenses :input');
input.each(function() {
    // Insert switch statement here??  Some other construct??
});

HTML: (Uses Bootstrap 3 classes)

FORM:

<form class="form-expenses form-horizontal" role="form" method="post" action="/profile/update">
    <div class="form-group">
        <label for="housing" class="control-label col-sm-3">Housing</label>
        <div class="input-group input-group-lg col-sm-9"> 
            <span class="input-group-addon">$</span> 
          <input type="text" class="form-control" name="housing" id="housing" />
        </div>
    </div>
    <div class="form-group">
        <label for="utilities" class="control-label col-sm-3">Utilities</label>
        <div class="input-group input-group-lg col-sm-9"> 
            <span class="input-group-addon">$</span>
          <input type="text" class="form-control" name="utilities" id="utilities" />
        </div>
    </div>
...
<button class="btn btn-lg btn-primary btn-block" id="update-expenses" type="submit"> Update</button>

</form>

OUTPUT:

<tr>
  <td>Housing</td>
  <td id="output-housing">$<?php echo $total['housing']?></td>
</tr>

<tr>
  <td>Utilities</td>
  <td id="output-utilities">$<?php echo $total['utilities']?></td>
</tr>
  • 写回答

2条回答 默认 最新

  • dqd3690 2013-12-15 01:44
    关注

    Something like this should work. Assumes the same prefixing relationship of output/input ID's

    $(function() {
      $('form.form-expenses').submit(function() {
        updateValues();
        return false/* prevent submit for demo only*/
      })
    })
    
    function updateValues(){
      $('.form-expenses :input').not('#update-expenses').each(function(){
        var $input=$(this), inputId=this.id;
        var curr=$('#output-'+inputId).text().replace("$", "");
        $input.val(function(i,val){
          return (1*(val ||0) + 1*curr).toFixed(2);
        })
      });
    }
    

    <kbd>DEMO</kbd>

    From a UI perspective, this seems very counter intuitive to change values that user just input.

    To create ajax data object instead of updating the display values:

    function getAjaxData(){
      var ajaxData={}
      $('.form-expenses :input').not('#update-expenses').each(function(){
        var $input=$(this), inputId=this.id;
        var curr=$('#output-'+inputId).text().replace("$", "");
        ajaxData[this.name] =(1*(val ||0) + 1*curr).toFixed(2);
      });
      return ajaxData
    }
    
    /* in submit handler*/
    
    $.post('path/to/server', getAjaxData(), function(response){/*do something with reponse*/})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab