简体   繁体   中英

jquery not working with underscore.js

i am trying to add input boxes on click. but its strange without underscore it is working means input boxes is generating but with underscore.js it is not working.

Also tested with alert("testing"); alert is successfully coming.

<div class="form-group">
                <div class="col-sm-10">
                    <div id="p_scents1">        
                        <a href="#" id="addScnt1">Add More</a>
                        <% _.each( type.size, function(i, listItem ){ %>
                                 <%= "<p><label for='p_scents1'><input id='TypeSize"+listItem+"' class='form-control' type='text' placeholder='Please enter  Type size' required='required' value='"+i+"' name='data[Type][size]["+listItem+"]'></label></p>" %>
                        <% }); %>
                    </div>
                </div>
            </div>

    <script type="text/javascript">
        $(function() {
            var scntDiv = $('#p_scents1');
            var i = $('#p_scents1 p').size();

            $('#addScnt1').live('click', function() { 
           alert("testing"); //tested . alert is working fine. but append is not working.
                $(scntDiv).append('<p><label for="p_scents1"><input id="TypeSize0" class="form-control" type="text" placeholder="Please enter Type size" required="required" name="data[Type][size]['+i+']"></label> <a href="#" id="remScnt1">Remove</a></p>');
                i++;
                return false;
            });

            $('#remScnt1').live('click', function() {
                if( i > 1 ) {
                    $(this).parents('p').remove();
                    i--;
                }
                return false;
            });
        });
    </script>

Since those 2 elements are dynamically building, You have to use delegate like this

 $(document).on('click', '#addScnt1', function () {
    var i = $('#p_scents1 p').size();         
     $(scntDiv).append('<p><label for="p_scents1"><input id="TypeSize0" class="form-control" type="text" placeholder="Please enter Type size" required="required" name="data[Type][size][' + i + ']"></label> <a href="#" id="remScnt1">Remove</a></p>');
     i++;
     return false;
 });

 $(document).on('click', '.remScnt1', function () {
      var i = $('#p_scents1 p').size();         
      if (i > 1) {
         $(this).parents('p').remove();
         i--;
     }
     return false;
 });

Edit

Instead of appending all the elements, troubleshoot the steps by adding elements one by one. First you can try like this,

$('#p_scents1').append("<span>test</span>");

Then add elements and findout which element causes the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM