I'm working on an ASP.NET Core project and need to get the value of the checked input[type="radio"]
when clicking on the inputs.
my HTMl codes are as following:
@if (Model.ProductColors.Any())
{
<div ><span >رنگ:</span><span id="colorValue"></span></div>
<div ><span >کدرنگ:</span><span id="colorCode"></span></div>
<div >
@{int j = 1;
}
@foreach (var item in Model.ProductColors)
{
<div onclick="doActiveRadioButton('color_@j')" id="div_color_@j" >
<input @((j==1)?"checked":"") type="radio" name="color" id="color_@j" data-bs-label="colorOption" value="@item.ColorId">
<label for="color1"><span style="background-image: url(/Images/ProductThumbs/@item.ImageName)"></span></label>
</div>
j ;
}
I've tried to get the value at the end of below codes:
<script>
function doActiveRadioButton(id) {
var slides = document.querySelectorAll(".productColor input");
console.log(slides.length);
for (var i = 0; i < slides.length; i ) {
slides[i].removeAttribute("checked");
}
var s = document.getElementById(id);
s.setAttribute("checked", "checked");
var g = document.querySelectorAll(".productColor label");
for (var i = 0; i < g.length; i ) {
g[i].style.border = "1px solid #e3e9ef";
}
var d = document.querySelector("#div_" id " label");
d.style.border = "1px solid #fe696a";
var radioId = document.querySelector('.productColor input[type = "radio"]:checked');
console.log(radioId);
var c = document.querySelector("#colorCode");
c.innerHTML = "green!";
}
</script>
When I use console.log()
to log the radioId, I mean the following part:
var radioId = document.querySelector('.productColor input[type = "radio"]:checked').value;
console.log(radioId);
For the first time, it works correctly and showing me the true radioId (for example 9), but when I click on the input for the second time or more, it shows me the following error:
Uncaught TypeError: Cannot read properties of null (reading 'value') at doActiveRadioButton (2008:1621) at HTMLDivElement.onclick (2008:745)
Would anybody explain it to me and give me some sulotions or alternatives please?
CodePudding user response:
Well, you look for the input that is checked. When it is checked you'll find it. When you uncheck it, it is no longer found and document.querySelector
returns null
. That means that the value
property no longer exists.
You might want to make a check first if the element is found or not.
const productColorInput = document.querySelector('.productColor input[type="radio"]:checked')
if (productColorInput !== null) {
const radioId = productColorInput.value;
console.log(radioId);
}
Or check the checked
property instead of querying a checked input. (This might be more solid as it always returns an element).
const productColorInput = document.querySelector('.productColor input[type="radio"]');
if (productColorInput.checked === true) {
const radioId = productColorInput.value;
console.log(radioId);
}