I am trying to save user input as an object, and save multiple objects in an array, but the $w(“#elementID”).value is returning as an empty string in JS, even though it’s not empty.
This is my code:
import wixData from 'wix-data';
$w.onReady(function () {
let member = {
fName: $w('#input2').value,
email : $w('#input5').value,
};
let Members = [];
Members.push(member);
$w('#button3').onClick(() => {
console.log(Members);
})
wixData.insert('JSTest', Member); // This returns an error, that it must be an object to save to database.
});
@ Rejoice Anya
Your code is in $w . onReady () function.
It is executed once when the page loads. When the page loads, there are no values in the inputs. This is why the console output shows in empty array.
Try this:
import wixData from 'wix-data';
let Members = [];
$w.onReady(function () {
$w('#firstNameInput').onChange(() => validateFieldsAndAddToArray())
$w('#emailInput').onChange(() => validateFieldsAndAddToArray())
$w('#button3').onClick(() => {console.log(Members);})
});
function validateFieldsAndAddToArray() {
if ($w('#firstNameInput').valid && $w('#emailInput').valid) {
let member = {
fName: $w('#firstNameInput').value,
email : $w('#emailInput').value,
};
Members.push(member);
}
wixData.insert('JSTest', Members);
}