Я создаю динамическую форму, в которой пользователь может динамически добавлять элементы. Я могу разрешить им добавлять текстовые поля, но я не уверен, как добавить в него раскрывающееся меню. Вот мой код jQuery
var addDiv2 = $('#addIngredient');
var i = $('#addIngredient p').size() + 1;
$('#addNewIngredient').on('click', function () {
$('<p> <input id="ingredient_' + i + '" name="ingredient[]" type=text"
value="" placeholder="Ingredient" />
<input id="quantity_' + i + '"
name="quantity[]" type=text" value="" placeholder="Quantity" />
<input id=alternative_' + i + '" name="alternative[]" type=text"
value"" placeholder="Alternative Ingredient" />
<a href=#" class="remNew2"> Remove </a> </p> ').appendTo(addDiv2);
Вот мой html
<div id="addIngredient">
<p>
<input type="text" id="ingredient_1" name="ingredient[]" value=""
placeholder="Ingredient"/>
<input type="text" id="quantity_1" name="quantity[]" value=""
placeholder="Quantity"/>
<input type="text" id="alternative_1" name="alternative[]" value=""
placeholder="Alternative Ingredient"/>
<select id="selectQuantity_1" name="quantityType[]">
<option value="grams">Grams</option>
<option value="ounces">Ounces</option>
<option value="Pounds">Pounds</option>
</select>
<a href="#" id="addNewIngredient">Add</a>
Я пробовал, но не могу это решить, помощь будет оценена!
Вот jsFiddle http://jsfiddle.net/3yFFr/
проигнорируйте бит ниже вставленного jQuery i, я должен был вставить все это для его работы.
Кажется, вы клонируете элементы в div. Я бы предложил вам продолжить использование .clone()
для этого.
См. Довольно упрощенный код. Теперь вы можете удалить элемент add и изменить его для удаления.
$('#addIngredient').clone()
.prop('id', 'addIngredient1').appendTo('ingredDiv');
А также старайтесь избегать использования id
если это необходимо.
Если вы хотите добавить строку для каждого щелчка "Добавить", я бы попробовал что-то вроде этого:
var addDiv2 = $('#addIngredient');
var formRow = addDiv2.find('p');
$('#addNewIngredient').on('click', function () {
formRow.clone(true, true).appendTo(addDiv2);
});
См. Этот jsFiddle для рабочего примера.
РЕДАКТИРОВАТЬ: Поскольку вам нужно держать ваши идентификаторы под контролем, я подстроил кое-что, что должно работать,
var addDiv2 = $('#addIngredient');
$('#addNewIngredient').on('click', function () {
// Clone the last input row, keeping the event handlers
var clonedRow = $('#addIngredient p').last().clone(true, true);
// We're going to examine all select and input elements
var all = clonedRow.find('select, input');
// A regular expression we can use to test if the id has numbers at the end
var numericPostfix = /\d+$/;
for (var i = 0; i < all.length; i++) {
var curr = $(all[i]);
// If current element has an id attribute
if (curr.attr('id') != undefined) {
var id = curr.attr('id');
// Rips off any trailing digits in element id
var idNum = numericPostfix.exec(id);
// Exec gives an array of matches, if it not null, choose the first match
if (idNum) {
idNum = idNum[0];
}
if (idNum) {
// Chop off last character
id = id.slice(0, (-1 * idNum.length));
// Increment and add the id number to the nextId
var nextId = id + (Number(idNum) + 1);
// Set the id attribute to nextId
curr.attr('id', nextId);
}
// Append to the DOM
clonedRow.appendTo(addDiv2);
}
}
});
В вашем коде вы не добавили меню выбора к тому, что вы добавили в jQuery. Посмотрите:
$('<p> <input id="ingredient_' + i + '" name="ingredient[]" type=text" value=""
placeholder="Ingredient" />
<input id="quantity_' + i + '" name="quantity[]" type=text" value=""
placeholder="Quantity" />
<input id=alternative_' + i + '" name="alternative[]"
type=text" value"" placeholder="Alternative Ingredient" />
<a href=#" class="remNew2"> Remove </a> </p> ').appendTo(addDiv2);
appendTo
, попробуйте добавить селектор (возможно, с чем-то вроде :nth-child(2)
вместо переменной.