Reputation: 129
I have two selects.
The first one displays male
of fem
and the second one display names depending on chosen mal
or fem
option. It works well. But I want to display these values in the new div. However, I can only access the mal
or fem
option. I guess it's because it is THIS. But how to add to this textContent a name? For example, create a div
with textContent male James
or fem Lola
? See code and link below
const namesArr = {
male: ['Tom', 'James', 'John', 'Jimmy', 'Angelo', 'Patrick', 'Ron'],
fem: ['Jemma', 'Samantha', 'Lola', 'Penny', 'Mary']
}
function show(){
document.querySelector('#name').textContent = ''
document.querySelector('.result').textContent = ''
let val = this.value
for(let i of Object.keys(namesArr)) {
if(val === i) {
namesArr[i].forEach(elem => {
newElem.value = i
newElem.textContent = elem;
document.querySelector('#name').style.display = 'inline-block'
document.querySelector('#name').append(newElem)
document.querySelector('.result').textContent =
this.options[this.selectedIndex].textContent
});
}
}
}
document.querySelector('#sex').addEventListener('click', show);
Upvotes: 1
Views: 43
Reputation: 4905
Need to add event listener name select too
const namesArr = {
male: ['Tom', 'James', 'John', 'Jimmy', 'Angelo', 'Patrick', 'Ron'],
fem: ['Jemma', 'Samantha', 'Lola', 'Penny', 'Mary']
}
function show(){
document.querySelector('#name').textContent = ''
document.querySelector('.result').textContent = ''
let val = this.value
for(let i of Object.keys(namesArr)) {
if(val === i) {
namesArr[i].forEach(elem => {
let newElem = document.createElement('option');
newElem.value = i
newElem.textContent = elem;
document.querySelector('#name').style.display = 'inline-block'
document.querySelector('#name').append(newElem)
document.querySelector('.result').textContent = this.options[this.selectedIndex].textContent
});
}
}
}
function nameChange(){
var sexDDL = document.getElementById("sex");
var sex = sexDDL.options[sexDDL.selectedIndex].text;
document.querySelector('.result').textContent = sex +" "+this.options[this.selectedIndex].textContent
}
document.querySelector('#name').addEventListener('click', nameChange);
document.querySelector('#sex').addEventListener('click', show);
<select name="sex" id="sex">
<option value="male">Male</option>
<option value="fem">Feminine</option>
</select>
<select name="name" id="name"></select>
<div class="result"></div>
Upvotes: 2