Reputation: 184
I would like to dynamically generate inputs, but I need to give them a different input name. First, I put the content of my html template in the variable:
var template = $("#question_template").html();
Then I add an index so I can distinguish each added block of inputs:
var question_html = "<div id='question_" + indice_question + "'>" + template + "</div>";
But now I'm trying to change the name of the inputs like this:
$(question_html).find('input').each(function(){
$(this).attr('name','question[question'+indice_question+']'+$(this).attr('name'));
});
The problem is my question_html
is not updated in the process, and when I do
console.log($(question_html).html());
The input names are the same that in my "template".
Here is the full code:
EDIT: snippet is not working but fiddle is : http://jsfiddle.net/W4Km8/7085/
indice_question = 0;
$('#add_question').on('click',function(){
var template = $("#question_template").html();
var question_html = "<div id='question_" + indice_question + "'>" + template + "</div>";
$(question_html).find('input').each(function() {
$(this).attr('name','question[question'+indice_question+']'+$(this).attr('name'));
console.log($(this).attr('name'));
});
console.log($(question_html).html());
$('#question_list').append(question_html);
indice_question++;
});
<div id="question_list">
</div>
<button type="button" id="add_question">Add question</button>
<div id="question_template" style="display:none">
<label for="question_content">Question content</label>
<input type="text" name="[question_content]"/><br/>
<input type="hidden" name="[id_question]" value=""/>
</div>
Upvotes: 1
Views: 1448
Reputation: 36703
Every $(question_html)
will be a different jQuery object.
Instead of creating the HTML String, you should create a jQuery Object to manipulate it. Because when later you were trying to access $(question_html)
it was just another jQuery object and not the previous one.
var question_html= $("<div id='question_"+indice_question+"'>" + template + "</div>");
question_html.find('input').each(function(){
$(this).attr('name', 'question[question' + indice_question +']' + $(this).attr('name'));
});
Now when you will do console log, the names will be changed
console.log(question_html.html());
Upvotes: 2