Reputation: 799
I have this code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h2>To Do</h2>
<form name="checkListForm">
<input type="text" name="checkListItem"/>
</form>
<div id="button">Add!</div>
<br/>
<div class="list"></div>
</body>
</html>
Javascript/Jquery:
$(document).ready(function()
{
$(button).click(function(){
var toAdd = $('input[name=checkListItem]').val();
$('.list').append('<div class="item">' + toAdd + '</div>');
});
$(document).on('click','.item', function(){
$(this).remove();
});
});
This code grabs a user's input, adds it to a list when you click a button, and removes the input from the list when you click on it within the div class item.
How can I make it so that I can return the value of "this"?
For example, if I add the word "test" to the list, and click on it to remove it.... how can grab the value of test from "this"?
Like.. document.write(this) returns [object HTMLDivElement].
I want document.write to return "test" if I click on it in the div.
I can't do document.write(toAdd) because toAdd doesn't exist in the second jquery ("on") function. Thanks.
Upvotes: 1
Views: 122
Reputation: 1513
You can retrieve the text inside the clicked item by $(this).text()
. So you can do something like document.write($(this).text())
before you remove the item.
Upvotes: 1
Reputation: 80639
$(document).ready(function () {
$('#button').on('click', function () {
var toAdd = $('input[name=checkListItem]').val();
$('.list').append('<div class="item">' + toAdd + '</div>');
});
$(document).on('click', '.item', function () {
alert( $(this).text() ); // You can have `.html()` here too.
$(this).remove();
});
});
Fiddle link is here.
Upvotes: 2
Reputation: 5374
Use .innerHTML
:
$(document).ready(function()
{
$(button).click(function(){
var toAdd = $('input[name=checkListItem]').val();
$('.list').append('<div class="item">' + toAdd + '</div>');
});
$(document).on('click','.item', function(){
document.write(this.innerHTML);
$(this).remove();
});
});
Upvotes: 1