I'm having problems reassigning the value of an object's property from inside a JavaScript/jQuery function.
I'm writing some basic validation on six input fields within a form element, ensuring the fields are not empty. Once all input fields have a value in them, I'd like to display additional input fields in the form that are initially hidden.
The problem I have is I can't update my object properties from within my function.
I'm passing a variable in a function, and it seems to be updated within my function but I'm not seeing the variable's value change globally.
Here's the object in the global scope that keeps track of whether the fields are validated:
var validationObject = {
titleValid: "n",
firstNameValid: "n",
lastNameValid: "n",
emailValid: "n",
contactEmailValid: "n",
contactSMSValid: "n"
}
For each field I'm calling a version of this function. I think the problem is here -- one of the arguments I'm passing in the function is 'firstNameValid':
function firstNameIsValid() {
return fieldHasValue($("input#field_firstName"), $("div#first_name_error"), firstNameValid);
}
$("input#field_firstName").on('change blur', firstNameIsValid);
The preceding function uses this function, which I'm planning to reuse with all input fields:
function fieldHasValue(field, label, validationProperty) {
var value = field.val().trim(); //Grab value without leading or trailing whitespace
if (value.length > 0) {
label.hide(); //hide error message
validationProperty = "y"; //set property in global object?
} else {
label.show();
validated = "n";
field.focus();
}
return (value.length > 0);
}
After running the function, the third parameter in the fieldHasValue function, 'validationProperty', is being used literally within the firstNameIsValid function. The result is my object becomes:
var validationObject = {
titleValid: "n",
firstNameValid: "n",
lastNameValid: "n",
emailValid: "n",
contactEmailValid: "n",
contactSMSValid: "n",
validationProperty: "y"
}
If you know how I can update the object from within the fieldHasValue() function, please send word.
validationObject[validationProperty] = "y";undefined, actually, unless you have awithstatement not showing. To pass the value, passvalidationObject.firstNameValid. To set the value, pass"firstNameValid"and use the code @halilcakar shows.return fieldHasValue({..}, {..}, firstNameValid);- what'sfirstNameValid? Hint: it's notvalidationObject.firstNameValid