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
3 Answers
Reset to default 10A 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
});