Doris Doris - 5 months ago 10
jQuery Question

Can method used in the .append() in JQuery?

I am new to JQuery. I want to use JQuery to realize a function that can take the content of the input and put the content into a list. Now I got a problem:
this is part of the HTML code.

<body>
<form name="checkListForm">
<input type="text" name="checkListItem"/>
</form>
<div id="button">Add!</div>
<br/>
<div class="list"></div>
</body>


This is the JQuery Code:

$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
$('.list').append('.div'.addClass('item').html(toAdd));
});
});


I am trying to realize this: When I input something and click the button, the content will be stored in the
toAdd
, and a new div with
class="item"
and
toAdd
content will be appended in the list. I know there is another correct method to realize this:

$('.list').append('<div class="item">' + toAdd + '</div>');


So I just wonder why my code does not work here?

Answer
  • Correct the typo at .val, it is method not property hence add ()(parenthesis)
  • $('<div>') will create jQuery object of empty div element

$(document).ready(function() {
  $('#button').click(function() {
    var toAdd = $('input[name=checkListItem]').val();
    $('.list').append($('<div>', {
      class: 'item',
      html: toAdd
    }));
  });
});
.item {
  border: 2px solid black;
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form name="checkListForm">
  <input type="text" name="checkListItem" />
</form>
<div id="button">Add!</div>
<br/>
<div class="list"></div>