0

I'm trying to use a drop down next to a simple number input within a section on a dynamic web page form. I am able to create a new section with a button, and I can use normal text or number fields within that section. However when I try and create a drop down within a section I cannot get it to work.

I can get the dropdown to work fine when its independent, just not within the dynamically created section.

document.getElementById('addVegetablesButton').addEventListener('click', function() {
  var newSection = document.createElement('fieldset');
  var legend = document.createElement('legend');
  legend.textContent = 'Vegetable';

  var newField1 = document.createElement('input');
  newField1.type = 'number';
  newField1.name = 'sectionField1';
  newField1.placeholder = 'Quantity';
    
  var newField2 = document.createElement('label');
  newField2.textContent = 'Vegetable type:';

  var newSelect = document.createElement('select');
  newSelect.name = 'dynamicSelect';

  var option1 = document.createElement('option');
  option1.value = 'option1';
  option1.textContent = 'Carrot';

  var option2 = document.createElement('option');
  option2.value = 'option2';
  option2.textContent = 'Brussel Sprout';

  newSelect.appendChild(option1);
  newSelect.appendChild(option2);
    
  newSection.appendChild(legend);
  newSection.appendChild(newField1);
  newSection.appendChild(newField2);
  document.getElementById('dynamicForm').appendChild(newSection);
});

With the above the first element (quantity) works fine, the label for the newField2 shows, but no drop down. I tried various configurations where the button woldn't even generate the section, the above is as close as I have come to it work.

2
  • You forgot to append newSelect: newSection.appendChild(newSelect); Commented Nov 18, 2024 at 16:45
  • Hadn't realised this wouldn't remain as a ref to newField2, you are correct though thank you very much! Commented Nov 18, 2024 at 17:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.