I looped through the radio with it ‘name’ to get the selected ‘term’ for it value then use a button to add data to database with other values.
const inputTerm = document.getElementsByName("terms")
propertyBtn.addEventListener("click", function () {
for (let i = 0; i < inputTerm.length; i++){
if(inputTerm[i].checked){
let pickedTerm = inputTerm[i].value
}
}
let propertyData = {
terms: pickedTerm,
title: inputTitle.value,
location: inputLocation.value,
};
push(addedPropertyInDB, propertyData);
});
With this code pickedTerm
is not defined, I want all propertyData
to get pushed as one to firebase database
3
Answers
After few trials and errors.
I created a separate function for looping and it worked as I wanted.
you need to declare pickedTerm outside the loop.
Its because the scope of the variable pickedTerm is only valid inside the if statement.
Scope in JavaScript
Scope is the current context of execution in which values and expressions are "visible" or can be referenced. If a variable or expression is not in the current scope, it will not be available for use.
JavaScript has the following kinds of scopes:
Read more on Scope
For your current script, you would need to declare the
pickedTerm
variable where on the scope where it is being accessed.And that’s it. Happy Coding!!