Javascript表从输入创建和填充

时间:2014-03-11 21:20:41

标签: javascript jquery

我有一系列输入(一些无线电和几个复选框),如下所示:

<input type="radio" id="rd1" value="100" name="radios" class="slot" />
    <label for="rd1">Description of Radio 1</label>
<input type="radio" id="rd2" value="500" name="radios" class="slot" />
    <label for="rd1">Description of Radio 2</label>
<input type="radio" id="rd3" value="300" name="radios" class="slot" />
    <label for="rd1">Description of Radio 3</label>

<input type="checkbox" id="cb4" value="400" name="cb4" class="slot" />
    <label for="cb4">Description of CB 4</label>
<input type="checkbox" id="cb5" value="800" name="cb5" class="slot" />
    <label for="cb5">Description of CB 5</label>
<input type="checkbox" id="cb6" value="750" name="cb6" class="slot" />
    <label for="cb6">Description of CB 6</label>
<input type="checkbox" id="cb7" value="525" name="cb7" class="slot" />
    <label for="cb7">Description of CB 7</label>

我现在正在尝试使用javascript创建一个表,该表将更新以显示第1列中的选定输入,第2列中的值,然后是底部的总行。 (该表是使用javascript生成的,因为它在同一页面上的4个不同选项卡上重复使用,因此通过将新的int传递给函数,每个东西都获得唯一的ID,因此没有冲突)。

表格的格式应为:

<table>
    <tbody>
        <tr>
            <th>Class</th>
            <th>Cost</th>
        </tr>
            <td>     <!— input ID (e.g. cb4) —> </td>
            <td>     <!—selected class cost —> </td>
        <tr>
        <tr>
            <td>Total: </td>
            <td id="costTotal"> <!— total of cost column —> </td>
        </tr>
    </tbody>
</table>

用于创建表的js非常有用,我会弄清楚最后一点,但我正在努力如何进行行插入。

当选中复选框时,应将其输入ID和相应的值插入表中,并使用总td然后进行更新以对其进行求和。如果取消选中复选框,则会删除该行的相应行。按升序添加新行的加分点(即如果选择了无线电1,则选择cb3,然后在cb2之后,选择时cb2的行显示在1和3之间)。

非常感谢任何有关此建议/建议/指导。

1 个答案:

答案 0 :(得分:0)

我不确定,我理解洞的想法。也许是这样:

$(document).on('change', '.tbl-src input', function(){
  createTable('.tbl-src', '.table-holder'); 

});


function createTable(selectorSrc, selectorDest){
 var html = "<table>\
    <tbody>\
        <tr>\
            <th>Class</th>\
            <th>Cost</th>\
        </tr>";

  var sum = 0;  
  $(selectorSrc).find('input:checked').each(function(index, el){
     var $el = $(el);
    var val = parseFloat($el.val());
    var name = $el.attr('name');
     sum += val;

     html += "<tr>\
      <td>" + name + "</td> \
      <td>" + val + "</td> \
      </tr>";

  });

        html += "<tr>\
            <td>Total: </td>\
            <td id=\"costTotal\">" + sum + "</td>\
        </tr>\
    </tbody>\
</table>";
  $(selectorDest).html(html);
}

试试此代码http://jsbin.com/cizovovo/2/

相关问题