Reputation: 13
<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>
I wanted the value of the rating that the user submits i.e if he submits 3 stars, I wanted the value 3 in javascript so that I would display a popup of "thank you ! you have submitted 3 stars."
Upvotes: 0
Views: 42
Reputation: 26
To get the value of the selected radio button, you can use the querySelector method to select the checked radio button and then access its value property.
<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>
Upvotes: 1