Brook Julias
Brook Julias

Reputation: 2105

jQuery, appending HTML string not working

When using the code below I am unable to add the HTML string to the innerHTML of the target HTMLElement. What am I doing wrong? Is there a better way to do this?

<html>
    <head>
        <title>Add HTML input with jQuery</title>
        <!--
         *  This code is meant to include the jQuery library v.1.9.1
         *  from Google API
         -->
        <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' type='text/javascript'></script>
        <script>
            $('document').ready(function(){
                $('#add').click(function(){
                    var src = $('#src');    // alert(src);
                    var trgt = $('#src');   // alert(trgt);
                    var x = null;
                    var child = null;
                    var str = null;

                    if(null != src.val()){
                        alert(1);
                        x = trgt.children().length;

                        str = '<input type="text" name="array[]" id="index' + x + '" value="' + src.val() + '" />';

                        trgt.html().append(str);


                        src.val() = null;
                    }else{
                        alert('src value is emppty');
                    }
                });
            });
        </script>
    </head>
    <body>
        <div id="box">
                <label></label> <input type="text" name="src" id="src" value="" /> <button id="add">+</button>
                <div id="trgt">
                </div>
        </div>
    </body>
</html>

Upvotes: 1

Views: 1824

Answers (2)

Robert Levy
Robert Levy

Reputation: 29073

var trgt = $('#src'); ... Your source and target selectors are the same.

Upvotes: 2

Mark S
Mark S

Reputation: 3799

This var trgt = $('#trgt') is not the only problem I noticed.

There is trgt.html().append(str); which should be trgt.append(str);.

And then src.val() = null;, are you trying to reset the <input> value? You can simply do it with src.val('');

See this jsfiddle.

Upvotes: 1

Related Questions