How can i add textbox value entered by user to label dynamically using jquery?
Hi How can i add textbox value on button click to the label l开发者_Go百科ike this
http://jsfiddle.net/NT4Zr/29/
In above code user can type his hobby and add into the form by using add hobby link. when user press add hobby link the textbox value should be added to the label and for each entry new label created dynamically.
after adding hobbies user can free to delete hobbies by using delete button.
how can i do that?
Would something like the below be what you're looking for?
<!-- The container into which new hobbies will be inserted -->
<ul id="hobbies">
</ul>
<form method="post" action="">
<!-- The form element the user will use to enter new labels.
Note that the value of the for attribute of the label element
matches the value of the id attribute of the input element -->
<label for="hobby">Hobby:</label><input type="text" id="hobby" /><br />
<a id="add-hobby">Add Hobby</a><br />
<input type="submit" id="saveStudentInfo" value="Save Details" />
</form>
<!-- $(handler) is a shorthand for $(document).ready(handler)
see http://api.jquery.com/ready/ -->
<script> // would be placed in the HEAD, of course
$(function (){
$('#add-hobby').click(function () {
// Extract the input value
var newHobbyText = $("#hobby").val();
// Create the list item to add
var $newHobbyListItem = $("<li></li>").text(newHobbyText);
// Create the delete link
var $deleteLink = $("<a></a>").text("Delete").css("margin-left","5px");
// Register a delete handler (could be done as part of the above line)
$deleteLink.click(function () {
$newHobbyListItem.remove();
});
// Add the delete link to the list item
$newHobbyListItem.append($deleteLink);
// Finally, add the new item to the DOM
$("#hobbies").append($newHobbyListItem);
});
});
</script>
Some notes on this implementation:
- I choose to use an unordered list over a table because it's less work and, arguably, more semantically correct.
- If you need to add an input element (or similar) to the form to track what hobbies have been added, that's simple enough to do (just follow the above pattern for building, appending, and removing elements; currently, the delete handler removes only the list item, but it could remove an input element as well. However, I wasn't sure how you planned to process this data, so it's not clear what the best information to place in the input elements would be.
- I removed a few HTML elements (e.g. the "Hobbies" heading, the cancel button) as they seemed to clutter the example. There's no reason they need to be omitted, but I was hoping to keep things concise.
精彩评论