提问人:Rohaib Razzaq 提问时间:11/9/2023 更新时间:11/9/2023 访问量:29
获取活动/已检查评级的值
Getting value of active/checked rating
问:
<div class="star-rating">
<input type="radio" id="5-stars" name="rating" value="5" />
<label for="5-stars" class="star">★</label>
<input type="radio" id="4-stars" name="rating" value="4" />
<label for="4-stars" class="star">★</label>
<input type="radio" id="3-stars" name="rating" value="3" />
<label for="3-stars" class="star">★</label>
<input type="radio" id="2-stars" name="rating" value="2" />
<label for="2-stars" class="star">★</label>
<input type="radio" id="1-star" name="rating" value="1" />
<label for="1-star" class="star">★</label>
</div>
<button id="btn" onclick="myFunction()"> Submit </button>
</div>
<script>
function myFunction(){
let rating = document.querySelector(); //what should I do here ?
console.log(rating);
}
</script>
我想要用户提交的评级值,即如果他提交 3 星,我想要 javascript 中的值 3,以便显示“谢谢!您已提交 3 颗星。
答:
1赞
Tahir1071a
11/9/2023
#1
若要获取所选单选按钮的值,可以使用 querySelector 方法选择选中的单选按钮,然后访问其 value 属性。
<div class="star-rating">
<input type="radio" id="5-stars" name="rating" value="5" />
<label for="5-stars" class="star">★</label>
<input type="radio" id="4-stars" name="rating" value="4" />
<label for="4-stars" class="star">★</label>
<input type="radio" id="3-stars" name="rating" value="3" />
<label for="3-stars" class="star">★</label>
<input type="radio" id="2-stars" name="rating" value="2" />
<label for="2-stars" class="star">★</label>
<input type="radio" id="1-star" name="rating" value="1" />
<label for="1-star" class="star">★</label>
</div>
<button id="btn" onclick="myFunction()">Submit</button>
<script>
function myFunction() {
const rating = document.querySelector(
'input[name="rating"]:checked',
).value;
console.log(rating);
alert(`Thank you! You have submitted ${rating} stars.`);
}
</script>
评论
let rating = document.querySelector("[name=rating]:checked").value;
?