Mr.Vibe
Mr.Vibe

Reputation: 418

Firefox issue with jQuery Clone

I am trying to create a list which can be appended by cloning elements. Every element has an input field inside it. Somehow, firefox fails to detect the input field when the clones and saves the field the second time. Below is the code I am using:

$('#add_xx').on('click', function(event) {        
    var clone = $('#hidden_base .new_xx').clone().attr('id', 'id' + Math.floor(Math.random() * 100));
    $('#save_xx').addClass('disabled');
    clone.find('input[name="name"]').attr('name', 'name' + Math.floor(Math.random() * 100)).val("").attr("id", "uid" + Math.floor(Math.random() * 100));
    $('ul.xx_list').append(clone);
    $('#xx_list').trigger('add_xx');
    return false;
});

Any help would be greatly appreciated.

Upvotes: 1

Views: 218

Answers (1)

Tomalak
Tomalak

Reputation: 338326

I'm not sure what causes the problem you see, but from your code sample I see that you try to do HTML templating. For very simple cases this works with jQuery alone, but it very quickly becomes difficult and ugly.

It's worthwhile to switch to an proper HTML templating engine (I suggest handlebars.js), it will solve this problem (and a few others, like separating JS code from layout and dealing with escaping issues).

var formSection = Handlebars.compile( $("#form-section-template").text() );
var counter = 0;

$(document)
.on("click", ".form-section-add", function () {
    var newSection = formSection({
        value: "Value #" + ++counter
    });
    $("#form-sections").append(newSection).find(":text").last().focus();
})
.on("click", ".form-section-remove", function () {
    $(this).closest(".form-section").remove();
});
#form-sections {
    list-style-type: none;
    padding: 0;
}
#form-sections > li {
    margin-bottom: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<script id="form-section-template" type="text/x-handlebars-template">
  <li class="form-section">
      <input type="text" name="entry[]" placeholder="Please enter a value..." value="{{value}}">
    <button class="form-section-remove">Remove line</button>
  </div>
</script>

<ul id="form-sections"></ul>
<button class="form-section-add">Add line</button>

Upvotes: 1

Related Questions