1

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>
1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

nice catch damn cant believe i didnt even notice that
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.