【问题标题】:Jquery: Adding multiple values to textboxes (round two)Jquery:向文本框添加多个值(第二轮)
【发布时间】:2010-03-07 05:37:11
【问题描述】:

我认为我没有尽我所能 last time 解释自己,所以我要再试一次。来自以下代码:

<div id="addons" class="grid_12 omega">
    <div class="addon"> 
        <span><input type="checkbox" name="addon_1" value="addon_1"></span>
        <span class="title">Title 1 here</span>
        <span class="cost">$<em>49</em></span>
        <p>Some text here</p>
    </div>
    <div class="addon"> 
        <span><input type="checkbox" name="addon_2" value="addon_2"></span>
        <span class="title">Title 2 here also</span>
        <span class="cost">$<em>95</em></span>
        <p>Some more text.</p>
    </div>
    <div id="summaries" class="hidden">
        <input type="button" id="totalme" name="totalme">
        <input type="text" value="" id="addons_titles" name="addons_titles"><!-- item titles array, from addons that are checked  -->
        <input type="text" value="" id="addons_cost" name="addons_cost"><!-- total cost, from addons that are checked -->
    </div>
</div>

对于所有“input[type=checkbox][checked]”(已检查插件),我正在尝试:

  • 总结从“.addon .title input[name]”到input#addons_titles的标题(每个标题用竖线字符分隔 - 例如:“Item 1 title |第 2 项标题")
  • 以及从“.addon .cost em”到input#addons_cost的总项目成本

我认为ObalixNick Craver 之前给出的代码是正确的,我只是不确定如何编辑它以仅对选定的插件执行此操作。

我也不确定如何触发它。我假设我应该在提交按钮上运行它,因此该数组只创建一次 - 否则标题可能会不断添加到一个曾经重复的数组中?

欣赏你的想法。

【问题讨论】:

    标签: jquery arrays sum


    【解决方案1】:

    我认为你的问题现在更清楚了。

    这将满足您的要求:

    $('#totalme').click(function () {
      var items = $('input:checkbox:checked'), // checked elements
          titles = [], // store the selected titles
          totalCost = 0; // store the total cost
    
      items.each(function () { // iterate over the checked elements
        var addon = $(this).closest('div.addon'), // get the closest div.addon
            title = $('span.title', addon).text(), // get title 
            cost = +$('span.cost em', addon).text(); // get cost coerced to number
    
        titles.push(title); // add the title
        totalCost += cost;  // add the cost to sumarize
      });
    
      $('#addons_titles').val(titles.join('|'));//join all titles with | as separator
      $('#addons_cost').val(totalCost); // show the amout
    
    });
    

    查看实时示例here

    【讨论】:

    • 太棒了——感谢你把它放在一个我能理解的例子中。还有一个问题——如何将“#course_cost”添加到总成本中?示例:jsbin.com/ibadi/6
    • +1 b/c 我什至从未考虑过 :checkbox 选择器的可能性。总是做长格式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 2015-08-10
    • 2013-12-21
    • 1970-01-01
    相关资源
    最近更新 更多