I have a reactJS application where I render a drop down select with the following code:
renderPrimary = (passedid,value) => {
if (value=="Primary") {
return (
<div className="col-9 text-left text_14">
<select id={passedid}>
<option value="Primary" selected>Yes</option>
<option value="Secondary">No</option>
</select>
</div>
)
} else {
return (
<div className="col-9 text-left text_14">
<select id={passedid}>
<option value="Primary">Yes</option>
<option value="Secondary" selected>No</option>
</select>
</div>
)
}
}
This will render a drop down with two values, either Primary or Secondary based on the passed parameter 'value'. In my first test case, value = "Primary" so the code with render the with a drop down with "Yes" and "No" and the "Yes" is selected.
When the user clicks on a button, I validate other elements in the DOM. I then try to pick up the value from the so I know if the user selected Yes or No. I do this with the following code:
if (formIsValid) {
var id = "benePorS"+(l+1);
var element = document.getElementById(id);
var id2 = "benePct"+(l+1);
var element2 = document.getElementById(id2);
var PorS = element.selectedIndex;
console.log("PorS: ", PorS);
if (PorS == 0) {
hasPrimary = true;
primaryPct = primaryPct + element2.value;
} else {
hasSecondary = true;
secondaryPct = secondaryPct + element2.value;
}
}
When I execute the code, I see the following in the console.log:
PorS: 0
but then I see this:
Uncaught TypeError: Cannot read property 'selectedIndex' of null
at Beneficiaryupdate.SaveBeneficiaryInformation
So it seems that I can access the selected value (when I select No, I see PorS: 1 in the console.log) but the error prevents the code from continuing.
This is from the developers tool elements tab showing the rendered html:
Why would I be getting this error message?

"benePct"+(l+1);Where is this in your DOM? What is the value ofl?element.selectedIndexbutelementis null. That means an element with that ID on the page was not found. Either your selector is wrong, the code is executing before the element is on the page, or there is no element with that ID. You don't provide enough code to answer those questions.