Question

When I write some text in the input field. And want it displayed below the input field, when pressing the submit button it disappears. I don't know why.

Live Demo

HTML:

<textarea id ="comments" cols="30" rows="3"></textarea>
            <input type="submit" value="Submit" id="submit"/> 
            <div id="divComments"></div>

Jquery:

function addComment(name1) {

        var container = $('divComments');
        var inputs = container.find('label');
        var id = inputs.length + 1;

        var div = $('<div />');

        $('<label />', {
            id: 'comment' + id,
            text: name1
        }).appendTo(div);

        div.appendTo(container);     
    }

    $('#submit').click(function () {
        addComment($('#comments').val());
        $('#comments').val("");
    });
Was it helpful?

Solution

You missed the # for id selector, change

var container = $('divComments');

to

var container = $('#divComments');

See the fixed demo.

OTHER TIPS

The selector for the divComments div is missing the # for the id selector.

function addComment(name1) {
    var container = $('#divComments');
    var inputs = container.find('label');
    var id = inputs.length + 1;
    var div = $('<div />');

    $('<label />', {
        id: 'comment' + id,
        text: name1
    }).appendTo(div);

    div.appendTo(container);
}

$('#submit').click(function () {
    addComment($('#comments').val());
    $('#comments').val("");
});

Working fiddle.

As well as fixing the following line to add a hash

    var container = $('#divComments');

you will also want to change the submit function:

$('#submit').click(function (e) {
    e.preventDefault();
    addComment($('#comments').val());
    $('#comments').val("");
});

This will stop the form actually been submitted (and reloading the page) - which is probably the reason for your text disappearing. If you don't have a form surrounding your inputs then you don't need to bother with the second part of this answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top