Fisrt Code
HTML
<div>
<select class="a">
<option value="1">aaa</option>
<option value="2">bbb</option>
</select>
<input class="b">
</div>
A.js
const a = (function initA() {
const a = document.querySelector('select.a');
a.addEventListener('change', function() {
b.setValue(this.value);
})
return {
value: () => a.value
}
})()
const b = (function initB() {
const b = document.querySelector('input.b');
b.addEventListener('keyup', function (){
if (this.value.startsWith(a.value()) === false) {
b.value = a.value();
}
})
return {
setValue: function (val) {
b.value = val;
}
}
})()
An event that initializes the input value with the select value when the select changes, and if the input value does not start with the select value, it initializes with the select value.
I thought it would be used in many places, so I moved the code and modularized it.
Common.js
export function initA() {
const a = document.querySelector('select.a');
a.addEventListener('change', function() {
b.setValue(this.value);
})
return {
value: () => a.value
}
}
export function initB() {
const b = document.querySelector('input.b');
b.addEventListener('keyup', function (){
if (this.value.startsWith(a.value()) === false) {
b.value = a.value();
}
})
return {
setValue: function (val) {
b.value = val;
}
}
}
A.js
const a = initA();
const b = initB();
But it occur Uncaught ReferenceError
const a = initA(b);
const b = initB(a);
The same goes for giving a variable.
how to solve problem?
Since a select
requires an input
to work properly and the other way around, I would just merge the two functions into one. Both of your functions are not really standalone. Also I prefer passing the elements instead of assuming select.a
and input.b
.
function initAB(a, b){
if(a && b){
a.addEventListener('change', function(b) {
b.value = this.value
}.bind(a, b));
b.addEventListener('keyup', function (a){
if (this.value.startsWith(a.value) === false) {
b.value = a.value;
}
}.bind(b, a));
return true
};
return false
};
initAB(
document.querySelector('select.a'),
document.querySelector('input.b')
);
<div>
<select class="a">
<option value="1">aaa</option>
<option value="2">bbb</option>
</select>
<input class="b">
</div>