theOzmic theOzmic - 1 month ago 8
HTML Question

Add input fields with JQuery not working

I am trying to create an input field dynamically, using JQuery. It works up to a point but then absolutely stops working, no error in console and I am confused, please help.

I will attach a snippet alongside the code so you can better understand what's happening.

I can't define the problem because I don't fully understand what's happening, but I can try:

When I create a color I also want to create a size under that color, it works for the first color but doesn't work for other colors. What am I doing wrong?



$(document).ready(function() {
$("#add-color").click(function() {
$("#color-input-house")
.html($("#color-input-house")
.html() + '<div class="form-group">' +
'<input type="text" class="form-control colors" placeholder="Color">' +
' <button type="button" class="add-size small btn btn-primary rounded form-control">Add Size</button>' +
' <button type="button" class="remove-size small btn btn-warning rounded form-control">Remove Size</button>' +
' <div class="size-input-house"></div></div>');
});
$("#remove-color").click(function() {
if ($(".colors").length !== 1) {
$(".add-size").last().remove();
$(".remove-size").last().remove();
$(".colors").last().remove();
}
});
$(".add-size").click(function() {
$(this)
.parent()
.find(".size-input-house")
.html($(".size-input-house")
.html() + '<div class="form-group">' +
'<input type="text" class="form-control sizes" placeholder="Size"></div>');
});
$(".remove-size").click(function() {
if ($(".sizes").length !== 1) {
$(".sizes").last().remove();
}
});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<input type="text" class="form-control colors" placeholder="Color">
<button type="button" class="add-size small btn btn-primary rounded form-control">Add Size</button>
<button type="button" class="remove-size small btn btn-warning rounded form-control">Remove Size</button>
<div class="size-input-house"></div>
</div>
<div id="color-input-house"></div>
<div class="form-group">
<div>
<button type="button" id="add-color" class="small btn btn-primary rounded form-control">Add Color</button>
<button type="button" id="remove-color" class="btn btn-warning rounded form-control">Remove Color</button>
</div>
</div>




Answer

when you add something with jquery and you want to apply click on them it is better to use following format in jquery:

$(document).on("click",".add-size",function(){
    $(this)
        .parent()
        .find(".size-input-house")
        .html($(".size-input-house")
            .html()+'<div class="form-group">' +
        '<input type="text" class="form-control sizes" placeholder="Size"></div>');
});

and the same way for another:

   $(document).on("click",".remove-size",function(){
        if($(".sizes").length !== 1){
            $(".sizes").last().remove();
        }
    });