Levan Charuashvili
Levan Charuashvili

Reputation: 163

I want to add a element with prepend jQuery

I want to add a new a element when I click the button but it doesnt work

<div id="add-container">
    <input type="text"> <button>add</button>
    <div id="megobrebi">
        <a>Levani</a>
        <a>Markozi</a>
        <a>Zuka</a>
        <a>Sandro</a>
    </div>
</div>
$(document).ready(function() {
    $('#add-container').on('click', 'button', function(){
        var value = $('#add-container input').val;
        var html = '<a>' + value + '</a>'
        $('$megobrebi').prepend(html);
    })
})

Upvotes: 0

Views: 41

Answers (3)

meDeepakJain
meDeepakJain

Reputation: 154

Change your script code to

$(document).ready(function() {
    $('#add-container button').on('click', function(e){
        e.preventDefault(); // You may use this line if you wish to disable the default functionality button.
        var value = $('#add-container input').val();
        var html = '<a>' + value + '</a>';
        $('#megobrebi').prepend(html);
    });
});

Upvotes: 0

mgarcia
mgarcia

Reputation: 6325

You have two errors in the handler for the click event on the button.

First, you need to call the jQuery val method in order to get the value of the input.

Second, the selector for the DOM element where you want to prepend is not right.

Therefore, the code should be:

$('#add-container').on('click', 'button', function(){
    var value = $('#add-container input').val();
    var html = '<a>' + value + '</a>'
    $('#megobrebi').prepend(html);
})

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49883

The last line should be

$('#megobrebi').prepend(html);

Upvotes: 0

Related Questions