Reputation: 13
In Javascript for HTML how can I create a new object instance of a class where the object name / variable name of a new object in the class comes from the text value of an input element?
In this example... I have a class called myClass and I've made one myClass object instance called Chickens with a property ‘myProperty’ with a value of 100. Say I wanted to use the name input element in the browser to make a new myClass object instance such as Dogs and set it's myProperty value to 49 with the property input element.
Here is my example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name" placeholder="name">
<input id="property" placeholder="property">
<button id="btn"></button>
</body>
<script src="rhythm-class.js"></script>
</html>
and
function myClass() {
this.myProperty
}
let chickens = new myClass()
chickens.myProperty = '100'
console.log(chickens)
let currObj = null
let currProp = null
document.querySelector('#name').addEventListener('change', (e)=> {
console.log(e.target.value)
currObj = e.target.value
let `${e.target.value}` = new myClass
})
document.querySelector('#property').addEventListener('change', (e)=> {
console.log(e.target.value)
currentProp = e.target.value
let `${currentObj}`.testProperty = e.target.value
})
document.querySelector('#btn').addEventListener('click', ()=> {
console.log(`${currentObj}`.testProperty)
})
Upvotes: 0
Views: 796
Reputation: 1429
function myClass(value) {
this.myProperty = value;
}
let chickens = new myClass("100");
console.log(chickens);
let form = document.querySelector("form");
let inputs = form.elements;
form.addEventListener("submit", (e) => {
e.preventDefault();
let nameField = inputs["name"];
let propField = inputs["property"];
// you can test here if both of the values are set
window[nameField.value] = new myClass(propField.value);
console.log(window[nameField.value].myProperty);
});
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<input id="name" placeholder="name">
<input id="property" placeholder="property">
<button id="btn">Submit</button>
</form>
</body>
</html>
Since every variable in JS is the property of the global object, we can make use of that here. Note that the global object is the window
. We set the property name of the global object to our instance name and then instantiate the class passing our input value.
Instead of using the global object, it is recommended you use a local object to store the variable names.
Upvotes: -1