单选按钮不通过ajax发送值

时间:2021-02-17 09:13:00

标签: php html jquery 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() {}
        });
    }

1 个答案:

答案 0 :(得分:1)

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

要解决此问题,请使用 :checked 选择器仅检索用户选择的值:

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