photoscene
photoscene

Reputation: 57

How to append into div

I'm novice in jquery. I want to prepend the value of an input into a new div. The problem is that the new value appears but also disappears immediately.This is the html code:

<form class="form-inline">
  <input type="text" name="input" value="Add an item here" onfocus="value=''" class="add-item" >
  <button type="submit" class="btn" name="submit"><img src="img/pipe.png" alt=""></button>
</form>

<div class="col-lg-12 list">
                        <div class="list-row">
                            <div class="trash"></div>
                            <div class="list-tag">
                                 <p>chicken and salt</p>
                            </div>
                            <div class="pipe"></div>
                        </div>
                        <div class="list-row">
                            <div class="trash"></div>
                            <div class="list-tag">
                                 <p>chicken and salt</p>
                            </div>
                            <div class="pipe"></div>
                        </div>
                    </div>

This is the js:

$('.add-item').keypress(function(event){
        if (event.keyCode === 13) 
        {
        var value = $(this).val();
        var addListItem = $('<div class="trash"></div> '+value+' <div class="pipe"></div>');
        $('.col-lg-12').prepend(addListItem); 
        }
    });

Could you help me what is the problem?

Upvotes: 0

Views: 76

Answers (3)

Paolo Casciello
Paolo Casciello

Reputation: 8202

Probably your page is reloaded after the js execution.

You have to stop the event propagation.

$('.add-item').keypress(function(event){
        if (event.keyCode === 13) 
        {
          var value = $(this).val();
          var addListItem = $('<div class="trash"></div> '+value+' <div class="pipe"></div>');
          $('.col-lg-12').prepend(addListItem);
          return false; // <-- this line
        }
    });

Pressing return in a form will submit it automatically.

Upvotes: 1

James Donnelly
James Donnelly

Reputation: 128781

It's because you're not calling event.preventDefault() from within your function, meaning your form submits as usual and ultimately causes the page to reload.

Simply add that inside your if statement:

if (event.keyCode === 13) 
{
    event.preventDefault();
    ...
}

Upvotes: 0

Shaunak D
Shaunak D

Reputation: 20626

Check this Demo Fiddle.

$('.add-item').keypress(function(event){
        if (event.keyCode === 13) 
        {
        var value = $(this).val();
        var addListItem = $('<div class="trash"></div> '+value+' <div class="pipe"></div>');
        $('.col-lg-12').prepend(addListItem); 
        }
});

$(".form-inline").submit(function(e){
        e.preventDefault();
});

Your problem was, the form was getting submitted on 'enter' press. So to prevent default action use e.preventDefault();

Upvotes: 0

Related Questions