How to add my 2 radio buttons value in jquery?
I have this code:
<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="he开发者_如何学运维alth" 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>
So now I have 2 radio star rating. What I want is when I click the submit score it will add up the 2 selected radio box. E.g when click radio button neat with the value of 1 and radio button health with the value of 2 then the result will show 3 coz 1+2=3 in my div class=test. Could anyone help me with this.
$('#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;
});
You need to use parseInt
to convert a String into a Number. Otherwise, you'll just be concatenating values onto a string.
$('#star-rating form').submit(function() {
var score = $(this).find('.neat-star').val()
+ $(this).find('.health-star').val();
$(this).find('.test').html(score);
return false;
});
Try this
(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;
});
});
精彩评论