如何在jquery中添加我的2个单选按钮值?

时间:2011-08-08 18:10:39

标签: javascript jquery html

我有这段代码:

<div id="star-rating">
<script type="text/javascript">
$(function(){
  $('#star-rating form').submit(function(){
  $('.test',this).html('');
   $('input',this).each(function(){
   if(this.checked) 
  //$('.test',this.form).append(''+this.name+': '+this.value+'<br/>');
$('.test',this.form).append(this.value);
});
 return false;
});
});
</script>

<form name="form1" method="post" action="<?=base_url();?>rate/student">
    <div class="dbtable">

    <table cellpadding="0" cellspacing="0" border="0"><tbody>
    <th colspan="4" align="left">Personal Appearance</th>
    <tr><td width="10px"></td><td width="60%">Neatness</td>
        <td width="20%">
            <input name="neat" type="radio" class="neat-star" value="1" title="Poor"/>
            <input name="neat" type="radio" class="neat-star" value="2" title="Fair"/>
        </td>
        </tr>

    <tr><td></td><td>Health</td>
        <td>
            <input name="health" type="radio" class="health-star" value="1" title="Poor"/>
            <input name="health" type="radio" class="health-star" value="2" title="Fair"/>
        </td>
        </tr>
    <tr><td></td><td align="right"></td>
        <td><input type="submit" value="Submit scores!" /></td>
        <td><div class="test Smaller">
            <span style="color:#FF0000">Results</span>
            </div>
        </td></tr>

所以现在我有2个无线电星评级。我想要的是当我点击提交分数时,它将添加2个选中的单选框。例如,单击单选按钮整洁,值为1,单选按钮运行状况值为2,则结果将在我的div class = test中显示3 coz 1 + 2 = 3。任何人都可以帮助我。

3 个答案:

答案 0 :(得分:1)

$('#star-rating form').submit(function() {
    $('.test', this).html('');
    var total = 0;
    $('input', this).each(function(){
        if(this.checked) {
            total += parseInt(this.value, 10);
        }
    }
    //Do something with total
    return false;
});

您需要使用parseInt将字符串转换为数字。否则,您只需将值连接到字符串上。

答案 1 :(得分:0)

$('#star-rating form').submit(function() {
    var score = $(this).find('.neat-star').val()
              + $(this).find('.health-star').val();
    $(this).find('.test').html(score);
    return false;
});

答案 2 :(得分:0)

试试这个

(function(){
  $('#star-rating form').submit(function(){
      var neatVal, healthVal;
      neathVal = $(this).find("input[name=neat]:checked").val();
      healthVal = $(this).find("input[name=health]:checked").val();
      $('.test', this).append(praseInt(neatVal) + parseInt(healthVal ));
      return false;
  });
});