Search code examples
javascriptjqueryhtmlonclickinsertafter

How do I prevent jQuery from adding an extra space ' ' in insertAfter function


This insertion code works just fine

<script>
    var X = 0;
    $(function () {
            X++;
            $("#AddNumber").on({ 'click': function () { $('<div class="form-row"><label><span>Another Number</span><input type="tel" name="Mobile' + X + '"><a><img onclick="$(this).closest("div").remove();" class="DeleteNumber" width="25" height="25" src="/Images/Delete.png" /></a></label></div>').insertAfter("#AddNumberAction"); } });
        }
    );

</script>

But when I check it after inserting its like this

Inspect Element on Google Chrome

which is making it not working properly..


Solution

  • That is about quote usage...

    The argument passed to .closest() is passed using double quotes. But double quotes already are wrapping the onclick= string...

    Since the whole jQuery element group you are creating is already wrapped using single quotes... Then, you should use an escaped set of single quotes around div... Like <img onclick="$(this).closest(\'div\').remove();"

    So try like this:

    <script>
      var X = 0;
      $(function () {
        X++;
        $("#AddNumber").on({ 'click': function () { $('<div class="form-row"><label><span>Another Number</span><input type="tel" name="Mobile' + X + '"><a><img onclick="$(this).closest(\'div\').remove();" class="DeleteNumber" width="25" height="25" src="/Images/Delete.png" /></a></label></div>').insertAfter("#AddNumberAction"); } });
      });
    
    </script>