Lewis Smith Lewis Smith - 4 months ago 18
HTML Question

Using JQuery to add another field and update hidden field, only working one way

JSFiddle link :JSFiddle

I have created a script using two examples I have found to do two different things, one add new fields at the users request as well as update a hidden field to show how many have been created. This is working if you add fields, i.e. the hidden field changes from 1 to 2 to 3... as the extra fields appear, but when you click remove this doesn't scale down properly below 2 and not always at all.

Any suggestions as to where I have gone wrong:

HTML:

<input id="bacon" type="hidden" class="bacon" value="1" name="testinput">
<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>

<div id="p_scents">
<p>
<label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
</p>
</div>


JQuery:

$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;

$('#addScnt').live('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
$('input#bacon').val(i);
i++;
return false;

});

$('#remScnt').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
$('input#bacon').val(i);
i--;
}
return false;
});
});

Answer

Firstly, live() has been deprecated and removed from jQuery several years ago, use on() with a current version of jQuery instead.
size() shouldn't be used either, you should be using length, and parents() isn't a good choice ... ever.

Secondly, you're creating elements with the same ID multiple times.

You should be checking the length of the collection, or in other words actually check how many elements there are on the page, and use that count whenever new elements are inserted or removed.

Try something more like this, it uses a more jQuery'ish syntax to create the element, which lets you add the event handler for removing directly.

$(function() {
    var scntDiv = $('#p_scents');

    $('#addScnt').on('click', function(e) {
        e.preventDefault();

        var i = $('.scents').length + 1,
            p = $('<p />', {
                'class': 'scents'
            }),
            l = $('<label />', {
                'for': 'p_scnts' + i
            }),
            f = $('<input />', {
                type : 'text',
                id   : 'p_scnt' + i,
                name : 'p_scnt' + i,
                size : '20',
                placeholder: "Input Value"
            }),
            a = $('<a />', {
                href: "#",
                text: 'Remove',
                on: {
                    click: function() {
                        p.remove();
                        $('#bacon').val($('.scents').length + 1);
                    }
                }
            });

        scntDiv.append(p.append(l.append(f), a));
        $('#bacon').val(i + 1);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="bacon" class="bacon" value="1" name="testinput">
<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>

<div id="p_scents">
  <p>
    <label for="p_scnts">
      <input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />
    </label>
  </p>
</div>

Comments