单选按钮不通过ajax发送值



这是一个星级评级系统,我正试图通过用户发送,包括对产品的评论和从20 = 1星,40 = 2星等评分…无论用户提交的是哪颗星,它都只取第一个值(100 = 5颗星),代码如下:

<input id="star5" name="star" type="radio" value="100" class="radio-btn hide" />
<label for="star5">☆</label>
<input id="star4" name="star" type="radio" value="80"
class="radio-btn hide" />
<label for="star4">☆</label>
<input id="star3" name="star" type="radio" value="60"
class="radio-btn hide" />
<label for="star3">☆</label>
<input id="star2" name="star" type="radio" value="40"
class="radio-btn hide" />
<label for="star2">☆</label>
<input id="star1" name="star" type="radio" value="20"
class="radio-btn hide" />
<label for="star1">☆</label>
<button type="submit" class="btn btn-block btn-main" id="commentbtn" onclick="comment()" > Send </button>

下面是ajax代码:

function comment() {
var comment = $('#comment').val();
var star = $('input[name=star]').val();
var product_id = '<?php echo $productID;?>';
var username = '<?php echo $_SESSION["username"];?>';
jQuery.ajax({
url: "comment.php",
data: {
comment: comment,
product_id: product_id,
star: star,
username: username
},
type: "POST",
success: function(data) {
swal({
text: "comment has been submitted",
icon: "success",
button: false,
timer: 1500,
});
$(document).ready(function(e) {
setTimeout(function() {
window.location.href = "single.php?product_id=" + product_id
}, 1500)
});
},
error: function() {}
});
}

这个问题是因为$('input[name=star]')选择了所有的单选输入,并且尝试从jQuery集合中检索值将始终只返回第一个元素的值。这就是为什么你得到的值总是100

要解决这个问题,使用:checked选择器只检索用户选择的值:

var star = $('input[name=star]:checked').val();

最新更新