I am wondering if it is okay to put html dom references in js oop. Although there are many JS OOP tutorials online, I haven't seen anything similar to what I am referring to. The code below is what I am referring to.
var form = {
fname : document.getElementById("fname").value;
};
say, for example the document.getElementById("fname").value
is a textbox with a value of "jacob". would form.fname = "jacob"
?
is this okay to do? is this a common practice to do?
I am not sure what you're trying to accomplish here. If you only need to retrieve the value that is currently in the input field, one time, ever, then this ought to be fine. If you're expecting the value of form.fname to continually update when the input value changes, you're not going to see that happen. You'd either need some handler tied to the change event of the input, or you'd need to do something more like this:
var form = {
fname: function () {
return document.getElementById('fname').value;
}
};
// Retrieving
form.fname()
Note that you have to invoke the fname function now, you can't simply refer to it as form.fname
.
If you really don't want to ever have to retype things ever, do something like this:
var fields = ['fname', 'lname', 'city', 'state'];
var form = {};
for (var i = 0, j = fields.length; i < j; ++i) {
form[fields[i]] = function () {
return document.getElementById(fields[i]).value;
}
}
You'll have to be a little bit more careful with that if you add things like dropdown lists to your form, because their .value
isn't as helpful, but you don't retype names if one changes.
And, if we really want to be fancy about it, you don't even have to type names when you get the values:
for (var i = 0, j = fields.length; i < j; ++i) {
console.log(form[fields[i]]())
}