Insert Option with Java

Asked

Viewed 804 times

0

I have a dynamic form. With a field radiobutton and a select. According to the value I select in the option I populate the list field with selected values.

Example.

Option 1 Option 2

When selecting option 1, the select field is populated with Item A Item B Item C

When selecting option 2, the select field is populated with Item X Item W

Biggest problem is how to insert options within the select javascript.

  • 1

    Welcome to Stackoverflow Samuel. Please post an excerpt of the code you already have to get a better idea of the problem, I suggest you read this help article from the site: How to create a Minimum, Complete and Verifiable example.

  • you can use jQuery in your project? or it must be in native Javascript without libraries.

  • Hi Paulo. I can’t use Jquery. It’s a dynamic form, and you’ve created scripts with the elements I created on the screen. John resolved in the answer below. It’s basically that way, just find out so he doesn’t keep adding up while I switch between options.

2 answers

5

Follow an example friend.. After you select an option, the options are created dynamically. With each radio change options change, reflecting only the desired values for that selection.

function populateOptions(opt) {
  let select = document.querySelector("select[name='selecao']");

  while (select.children.length) {
    select.removeChild(select.lastChild);
  }

  // Cria option "default"
  let defaultOpt = document.createElement('option');
  defaultOpt.disabled = true;
  defaultOpt.selected = true;
  defaultOpt.textContent = 'Selecione uma opção';
  select.appendChild(defaultOpt);

  opt.forEach(function(option) {
    let optEl = document.createElement('option');
    optEl.value = option.value;
    optEl.textContent = option.text;
      
    select.appendChild(optEl);

  });
}


document.querySelectorAll("input[type='radio']")
  .forEach(function(radio) {
    radio.addEventListener('change', function(evt) {
      
      switch (parseInt(this.value)) {
        case 1:
          populateOptions([{
              value: "A",
              text: "Opção A"
            },
            {
              value: "B",
              text: "Opção B"
            }
          ]);
          break;

        case 2:
          populateOptions([{
              value: "C",
              text: "Opção C"
            },
            {
              value: "D",
              text: "Opção D"
            }
          ]);
          break;
      }
    });
  });
<label>
  Opção 1
  <input type="radio" name="opt" value="1">
</label>
<label>
  Opção 2
  <input type="radio" name="opt" value="2">
</label>

<select name="selecao">
  <option disabled selected>Selecione uma opção</option>
</select>

  • Thank you my friend!!! I tested the codes and they worked too.

2


I made a small example here using only Javascript. See:

[...document.getElementById('form').elements].forEach((field) => {
  field.addEventListener('change', () => {
    if (field.value === 'opcao2') {
      createOptions(2);
    } else {
      createOptions(3);
    }
  });
});

function createOptions(quantidade) {
  let fieldSelect = document.getElementById('select');
  cleanOptionsSelect(fieldSelect);
  for (let i = 0; i < quantidade; i++) {
    let option = document.createElement('option');
    option.text = 'Opção ' + i;
    fieldSelect.append(option);
  }
}

function cleanOptionsSelect(fieldSelect) {
  fieldSelect.innerHTML = '<option value="valor1">Selecione uma opção</option>';
}
<form id="form">
    <input type="radio" id="opcao1" name="opcao" value="opcao1" />
    <label for="opcao1">Opção 1</label>
    <input type="radio" id="opcao2" name="opcao" value="opcao2" />
    <label for="opcao2">Opção 2</label>
</form>

<fieldset>
  <legend>Campo select</legend>
  <select name="select" id="select">
    <option value="valor1">Selecione uma opção</option>
  </select>
</fieldset>

Remarks:

  • The algorithm is compatible with most browsers, but probably won’t work in IE by using ES6.
  • 1

    Oh that cool guy. That’s right!!!!. I’d just have to figure out how to not keep adding up the options while alternating between options.

  • I’ll do it right here :D

  • @samueltomkelski changed! If my reply helped you or served as reply do not forget to mark as reply!

  • recommend using the event change instead of the event click for a number of reasons.

  • Solved, the algorithm adapts easily. Thanks for the reminder :) Hadn’t noticed

  • 1

    A hint is to put the attribute value value in the html of input[type=radio] as 2 and 3 and in the third line of the javascript code you call directly the function createOptions(this.value) :D

Show 1 more comment

Browser other questions tagged

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