Scroll through a JS object again after swapping the <option> inside a <select>

Asked

Viewed 49 times

0

I need to scroll through an object again after changing the option in the tag

That’s my little object:

const data = {
    "MG": [{ "slug": "belo-horizonte", "nome": "Belo Horizonte", "num": 20 }],
    "SP": [{ "slug": "sao-paulo", "nome": "São Paulo", "num": 40 }]
} 

And this is the select I created.

<label>Quantos módulos fiscais a sua propriedada tem:</label>
<select id="fiscalModule">
  <option value="minifundio">até 1 módulo fiscal</option>
  <option value="smallPropertie">de 1 até 2 módulos fiscais</option>
</select>

And every time I change the options, I need to switch these Divs:

<div>
  <label for="propertieClassification">Classificado como</label>
  <p readonly='readonly' type="text" style="text-size-adjust: 10%" id="propertieClassification"></p>
</div>
<fieldset>
  <div>
    <h5 style="color:blueviolet">Verificar a quantidade de faixa mínima para cada caso</h5>
    <label for="app_margem_corrego">APP em margens de córrego (m)</label>
    <p type="text" style="text-size-adjust: 10%" id="app_margem_corrego"></p>
  </div>
  <div>
    <label for="app_nascente">APP em torno de nascentes (m)</label>
    <p readonly='readonly' type="text" style="text-size-adjust: 10%" id="app_nascente"></p>
  </div>

  <div>
    <label for="reseva_legal">Área de reserva Legal</label>
    <p readonly='readonly' type="text" style="text-size-adjust: 10%" id="reseva_legal"></p>
  </div>

Here comes the JS:

var selectState = document.querySelector('select[id=state');
// populate select state option with data structure
selectState.options[selectState.options.length] = new Option('---', '---')
for (var key in data) {
    selectState.options[selectState.options.length] = new Option(key, key)
}

// find municipies value inside the object
let selectMunicipies = document.querySelector('select[id=municipie]');
selectMunicipies.options[selectMunicipies.options.length] = new Option('---', '---')
for (var key of Object.keys(data)) {
    for (var city of data[key]) {
        selectMunicipies.options[selectMunicipies.options.length] = new Option(city.nome, city.slug)
    }
}


//onChange if it's isMinifundio
document.querySelector('select[id=municipie]').addEventListener('change', function() {
    const state = data[selectState.options[selectState.selectedIndex].value]
    let current = document.querySelector('select[id=fiscalModule]');
    let isMinifundio = current.options[current.selectedIndex].value == 'minifundio' ? true : false;
    console.log(this.value);
    console.log('state', state);
    var municipie = state.find(x => x.slug === this.value)
    console.log('find', find);
    if (isMinifundio) {
        document.querySelector('input[id=module]').value = municipie.num;
        document.querySelector('p[id=propertieClassification]').innerHTML = 'Minifundio';
        document.querySelector('p[id=app_margem_corrego]').innerHTML = '5 metros';
        document.querySelector('p[id=app_nascente]').innerHTML = '15 metros';
        document.querySelector('p[id=reseva_legal]').innerHTML = 'A mata que já existe na propriedade';

    }
})


//onChange if it's smallPropertie
document.querySelector('select[id=municipie]').addEventListener('change', function() {
    const state = data[selectState.options[selectState.selectedIndex].value]
    let current = document.querySelector('select[id=fiscalModule]');
    let isSmallPropertie = current.options[current.selectedIndex].value == 'smallPropertie' ? true : false;
    var municipie = state.find(x => x.slug === this.value)
    if (isSmallPropertie) {
        document.querySelector('input[id=module]').value = municipie.num;
        document.querySelector('p[id=propertieClassification]').innerHTML = 'pequena propriedade';
        document.querySelector('p[id=app_margem_corrego]').innerHTML = '8 metros';
        document.querySelector('p[id=app_nascente]').innerHTML = '15 metros';
        document.querySelector('p[id=reseva_legal]').innerHTML = 'A mata que já existe na propriedade';
    }
})

Once a state/municipality is selected (Ex: "MG/Belo Horizonte"), I want the values to change when I switch from "up to 1 fiscal module" to "up to 2 fiscal modules"

1 answer

0

You don’t need an event change for each option of select, just create a single event and test the value of select within it.

I made an example with the code you passed:

const data = {
    "MG": [{ "slug": "belo-horizonte", "nome": "Belo Horizonte", "num": 20 }],
    "SP": [{ "slug": "sao-paulo", "nome": "São Paulo", "num": 40 }]
}

var selectState = document.querySelector('#state');
selectState.options[selectState.options.length] = new Option('---', '---')
for (var key in data) {
    selectState.options[selectState.options.length] = new Option(key, key)
}

let selectMunicipies = document.querySelector('#municipie');


selectState.addEventListener('change', function() {
  selectMunicipies.innerHTML = "";
  if(selectState.value == "---") return;
  selectMunicipies.options[selectMunicipies.options.length] = new Option('---', '---')
  for (var city of data[selectState.value]) {
    selectMunicipies.options[selectMunicipies.options.length] = new Option(city.nome, city.slug)
  }
})

//onChange if it's smallPropertie
document.querySelector('#fiscalModule').addEventListener('change', function() {
    // Pegando o estado selecionado
    var state = undefined;
    if(selectState.value != "---")
      state = data[selectState.value];
    // Pegando o município selecionado
    var municipie = undefined;
    if (state)
      municipie = state.find(x => x.slug === selectMunicipies.value);
    
    if (municipie)
      document.querySelector('#module').innerHTML = municipie.num;
    if (this.value == "minifundio") {
        document.querySelector('#propertieClassification').innerHTML = 'Minifundio';
        document.querySelector('#app_margem_corrego').innerHTML = '5 metros';
        document.querySelector('#app_nascente').innerHTML = '15 metros';
        document.querySelector('#reseva_legal').innerHTML = 'A mata que já existe na propriedade';

    } else if (this.value == "smallPropertie") {
        document.querySelector('#propertieClassification').innerHTML = 'pequena propriedade';
        document.querySelector('#app_margem_corrego').innerHTML = '8 metros';
        document.querySelector('#app_nascente').innerHTML = '15 metros';
        document.querySelector('#reseva_legal').innerHTML = 'A mata que já existe na propriedade';
    }
})
<label>Estado:</label>
<select id="state"></select>
<label>Município:</label>
<select id="municipie"></select>
<label>Quantos módulos fiscais a sua propriedada tem:</label>
<select id="fiscalModule">
  <option value="minifundio">até 1 módulo fiscal</option>
  <option value="smallPropertie">de 1 até 2 módulos fiscais</option>
</select>

<div>
    <label for="module">Module</label>
    <p type="text" style="text-size-adjust: 10%" id="module"></p>
</div>

<div>
  <label for="propertieClassification">Classificado como</label>
  <p style="text-size-adjust: 10%" id="propertieClassification"></p>
</div>
<fieldset>
  <div>
    <h5 style="color:blueviolet">Verificar a quantidade de faixa mínima para cada caso</h5>
    <label for="app_margem_corrego">APP em margens de córrego (m)</label>
    <p style="text-size-adjust: 10%" id="app_margem_corrego"></p>
  </div>
  <div>
    <label for="app_nascente">APP em torno de nascentes (m)</label>
    <p style="text-size-adjust: 10%" id="app_nascente"></p>
  </div>

  <div>
    <label for="reseva_legal">Área de reserva Legal</label>
    <p style="text-size-adjust: 10%" id="reseva_legal"></p>
  </div>
</fieldset>

Besides, I noticed you always use tag[property=value] to select an element, including by id. There are other simpler ways to do this, such as using # to indicate that the search is by id or . to indicate that it is by class. Take a look at this link about selectors.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.