最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - add li element in ul using jquery - Stack Overflow

programmeradmin4浏览0评论

I try make simple todo list. This is my html code:

<form>
   Task: <input type="text" name="task" id="input">
   <button>Submit</button>
</form>

<br>

<h2>What you need to do</h2>
<ul id="list">

</ul>

Then I try use jquery to read from i input field and apppend to existing ul element. But when i try it in chrome my new added element show me for half of second and remove. Here is my js code:

  $(document).ready(function() {
    $('button').click(function() {
            var new_task = $('#input').val();
            $('#list').append('<li>'+new_task+'</li>');
    });
  });

I try make simple todo list. This is my html code:

<form>
   Task: <input type="text" name="task" id="input">
   <button>Submit</button>
</form>

<br>

<h2>What you need to do</h2>
<ul id="list">

</ul>

Then I try use jquery to read from i input field and apppend to existing ul element. But when i try it in chrome my new added element show me for half of second and remove. Here is my js code:

  $(document).ready(function() {
    $('button').click(function() {
            var new_task = $('#input').val();
            $('#list').append('<li>'+new_task+'</li>');
    });
  });
Share Improve this question edited Jun 19, 2013 at 5:55 vivek salve 9911 gold badge10 silver badges20 bronze badges asked Jun 19, 2013 at 5:47 SuperManEverSuperManEver 2,3626 gold badges30 silver badges39 bronze badges 2
  • 1 Your form is submitted when you click your button, and so your page reloads. – nix Commented Jun 19, 2013 at 5:50
  • jsfiddle.net/ishankdubey/QBrPn – Ishank Commented Jun 19, 2013 at 5:52
Add a comment  | 

3 Answers 3

Reset to default 10

A button inside a form has a default type of submit, and will submit the form, you need to prevent that or set a different type on the button :

$(document).ready(function() {
    $('button').on('click', function(e) {
        e.preventDefault();
        var new_task = $('#input').val();
        $('#list').append('<li>'+new_task+'</li>');
    });
});

Try this

HTML

<form>
  Task: <input type="text" name="task" id="input">
  <button>Submit</button>
  <br>

 <h2>What you need to do</h2>
 <ul id="list">

 </ul>
</form>

JS

$(document).ready(function() {
 $('button').click(function() {

  var new_task = $('#input').val();
  $('#list').append('<li>'+new_task+'</li>');
  return false;
 });
});

Demo

You must return false; at the end of your function:

$('button').click(function() {
  var new_task = $('#input').val();
  $('#list').append('<li>'+new_task+'</li>');
  return false;   // This is new line of code
});
发布评论

评论列表(0)

  1. 暂无评论