2014-12-24 5 views
-2

Я хочу, чтобы пользователь мог создать неопределенное количество вопросов. Как только пользователь создал один вопрос, я хочу, чтобы появился еще один вопрос (вопрос 2) и т. Д.Как дублировать div, установив флажок?

Как бы я это сделал?

Благодаря

+0

Вам действительно нужно разработать немного больше об этом! –

+0

Итак, как только пользователь вводит заголовок и описание в текстовые поля, они щелкают текстовым полем, чтобы сказать, что он завершен, и ниже появится следующий набор текстовых полей, чтобы они могли ввести свой второй вопрос. После того, как они ввели все вопросы, они могут нажать кнопку, чтобы отправить данные. –

+1

Пожалуйста, покажите код, который вы пробовали, и какая часть его не работает. – dg99

ответ

0

вы можете попробовать что-то вроде этого

HTML

<div class="input-container"> 
    <input class="question" placeholder="Question" type="text"/> 
</div> 

<div class="add-option">+</div> 

JS

//click the '+' sign 
$(".add-option").click(function(){ 

    //find the first input and clone it then append it to the container 
    $(".input-container input:first").clone().appendTo(".input-container"); 

    //clear any value from the next input had there been any added 
    $(".input-container input:last").val(""); 
}); 

FIDDLE

UPDATE

я ушел из часть о флажком, с точки зрения пользовательского интерфейса, я не думаю, что вам нужно checkbox, чтобы убедиться в этом, не уверен, что он предлагает «это сделано, и я хочу двигаться дальше», но это вам решать. Вот новый скрипку

HTML

<div class="input-container"> 
    <input class="question" placeholder="Question" type="text"/> 
</div> 

<div class="add-option"><input type="checkbox"/></div> 

JS

//click the checkbox 
$(".add-option input[type=checkbox]").click(function(){ 

//find the first input and clone it then append it to the container 
$(".input-container input:first").clone().appendTo(".input-container"); 

//clear any value from the next input had there been any added 
$(".input-container input:last").val(""); 

//reset the checkbox 
$(this).prop("checked", false); 
}); 

NEW FIDDLE

+0

Хорошее спасибо, каковы имена дублированных текстовых полей? –

+0

@JoeTindall жаль печатать слишком быстро: вы можете назвать их чем угодно. Вы можете добавить к ним уникальное имя или номер, когда вы клонируете их, я упустил часть об этом флажке, я обновил свой ответ с новой скрипкой – jmore009

+0

Спасибо, очень помог! –

0

Я хотел бы сделать что-то вроде:

function addClone() { 
 
    var cloned = document.getElementById('test').cloneNode(true); //clone the element 
 
    document.body.appendChild(cloned); //add the cloned element to the page 
 
}
<div id='test'>iadwjoam</div> 
 
<input type="checkbox" id="xxx" name="xxx" onchange="addClone()" />

cloneNode() - https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode

0

В JavaScript вы можете сделать, как этот

var i = 0; 
 

 
function addMore() { 
 
    i++; 
 
    var parentDiv = document.createElement("div"); 
 

 
    var childLabel = document.createElement("label"); 
 
    childLabel.appendChild(document.createTextNode("Enter Value " + i)); 
 

 
    var childTextBox = document.createElement("input"); 
 
    childTextBox.type = "text"; 
 
    childTextBox.id = "txtInput" + i; 
 

 
    var childCheckBox = document.createElement("input"); 
 
    childCheckBox.type = "checkbox"; 
 
    childCheckBox.onchange = addMore; 
 

 
    parentDiv.appendChild(childLabel); 
 
    parentDiv.appendChild(childTextBox); 
 
    parentDiv.appendChild(childCheckBox); 
 
    document.body.appendChild(parentDiv); 
 

 
}
<div> 
 
    Add Items 
 
    <input type="checkbox" onchange="addMore()"> 
 
</div>

Надеется, что это поможет

0

Вот более или менее то, что я хотел бы сделать, используя чистый JavaScript (см комментариев для объяснения)

// Create a copy of a blank Question node 
 
question_template = document.getElementById("questions").firstElementChild.cloneNode(true); 
 
// A nice cloning wrapper 
 
new_question = function(){return question_template.cloneNode(true);}; 
 
// Something to do when the user is finished putting in questions 
 
alrt = function(){ 
 
    alert(Array.prototype.map.call(document.getElementById(
 
     "questions").getElementsByTagName("input"), 
 
     function(elt){return elt.value;})); 
 
}; 
 
// Hook for when text is placed in textbox 
 
addnew = function(){ 
 
    // Remove the event listener (If you don't do this, then on every 
 
    // keystroke a new box will be created 
 
    document.getElementById("questions").lastElementChild.oninput = function(event){}; 
 
    // Add a new line 
 
    document.getElementById("questions").appendChild(document.createElement("br")); 
 
    // Add a new question box 
 
    document.getElementById("questions").appendChild(new_question()); 
 
};
<div id="questions"> 
 
<input type="text" oninput="addnew()"/> 
 
</div> 
 
<input type="button" value="Done" onclick="alrt()"/>

UPDATE: Я только что видел ваша разработка в разделе комментариев главного сообщения. Вы могли бы реализовать что-то вроде этого:

// Create a copy of a blank Question node 
 
question_template = document.getElementById("questions").firstElementChild.cloneNode(true); 
 
// A nice cloning wrapper 
 
new_question = function(){return question_template.cloneNode(true);}; 
 
// Something to do when the user is finished putting in questions 
 
alrt = function(){ 
 
    alert(Array.prototype.map.call(document.getElementById(
 
     "questions").getElementsByTagName("input"), 
 
     function(elt){return elt.value;})); 
 
}; 
 
// Hook for when text is placed in textbox 
 
addnew = function(){ 
 
    // Add a new line 
 
    document.getElementById("questions").appendChild(document.createElement("br")); 
 
    // Add a new question box 
 
    document.getElementById("questions").appendChild(new_question()); 
 
};
<div id="questions"> 
 
    <input type="text"/> 
 
    </div> 
 
<input type="button" value="Add Another" onclick="addnew()"/> 
 
    <input type="button" value="Done" onclick="alrt()"/>

Это может быть реализовано с большинством любого input элемента с нужными событиями. Школы W3 имеют a nice reference, если вам это нужно.