Создание новых выпадающих списков с помощью кнопки

0

Таким образом, у меня есть этот код, который создает новые текстовые области, я надеялся, что кто-то покажет мне, как изменить код, чтобы вместо этого создать новый раскрывающийся список. Содержимое списка будет одинаковым в каждом поле.

Я думаю, что это случай с небольшими изменениями в javascript.

JAVASCRIPT

        var counter = 0;

  function addNew() {

// Get the main Div in which all the other divs will be added
var mainContainer = document.getElementById('mainContainer');

// Create a new div for holding text and button input elements
var newDiv = document.createElement('div');

// Create a new text input
var newText = document.createElement('input');
newText.type = "text"; 

//for testing
newText.value = counter++;

// Create buttons for creating and removing inputs
var newAddButton = document.createElement('input');
newAddButton.type = "button";
newAddButton.value = " + ";

var newDelButton = document.createElement('input');
newDelButton.type = "button";
newDelButton.value = " - ";

// Append new text input to the newDiv
newDiv.appendChild(newText);

// Append new button inputs to the newDiv
newDiv.appendChild(newAddButton);
newDiv.appendChild(newDelButton);

// Append newDiv input to the mainContainer div
mainContainer.appendChild(newDiv);

// Add a handler to button for deleting the newDiv from the mainContainer
newAddButton.onclick = addNew;

newDelButton.onclick = function() {
        mainContainer.removeChild(newDiv);
 };
}

HTML

             <select name="text">
                <option value="t1">t1</option>
                <option value="t2">t2</option>
                <option value="t3">t3</option>
              </select>
              <input type="button" value=" + " onClick="addNew();">
            </div>
Теги:
html-select

1 ответ

1

Большой вопрос, вот решение, которое вы можете реализовать довольно легко с учетом вашего существующего кода.

Вместо (часть вашего существующего кода):

// Create a new text input
var newText = document.createElement('input');
newText.type = "text"; 

//for testing
newText.value = counter++;

// Append new text input to the newDiv
newDiv.appendChild(newText);

Использование:

// create dropdown element and one option element
var newDropdown = document.createElement('select'),
    newDropdownOption = document.createElement("option");

// assign 'value' and 'text' properties to the option element   
newDropdownOption.value = "value1";
newDropdownOption.text = "option 1";

// add the option to the dropdown DOM node
newDropdown.add(newDropdownOption);

// add dropdown to mainContainer
newDiv.appendChild(newDropdown);

Надеюсь, это поможет!

EDIT: здесь полный рабочий код. вы должны быть в состоянии взять это отсюда!

function addNew() {

            // Get the main Div in which all the other divs will be added
            var mainContainer = document.getElementById('mainContainer');

            // Create a new div for holding text and button input elements
            var newDiv = document.createElement('div');

            // Create a new text input
            var newDropdown = document.createElement('select');

            newDropdownOption = document.createElement("option");
            newDropdownOption.value = "value1";
            newDropdownOption.text = "option 1";

            newDropdown.add(newDropdownOption);

            // Create buttons for creating and removing inputs
            var newAddButton = document.createElement('input');
            newAddButton.type = "button";
            newAddButton.value = " + ";

            var newDelButton = document.createElement('input');
            newDelButton.type = "button";
            newDelButton.value = " - ";

            // Append new text input to the newDiv
            newDiv.appendChild(newDropdown);

            // Append new button inputs to the newDiv
            newDiv.appendChild(newAddButton);
            newDiv.appendChild(newDelButton);

            // Append newDiv input to the mainContainer div
            mainContainer.appendChild(newDiv);

            // Add a handler to button for deleting the newDiv from the mainContainer
            newAddButton.onclick = addNew;

            newDelButton.onclick = function() {
                    mainContainer.removeChild(newDiv);
            };
        }

Добавление HTML: я ушел из HTML, который вы предоставили, так что это должно работать нормально.

<div id="mainContainer">
    <select name="text">
        <option value="t1">t1</option>
        <option value="t2">t2</option>
        <option value="t3">t3</option>
    </select>
    <input type="button" value=" + " onClick="addNew();">
</div>
  • 0
    Спасибо за ваш ответ, я не смог правильно создать изменения, кнопка больше не работает с новым кодом.
  • 0
    понял - я добавил полный рабочий код в свой ответ. удачи!
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню