March 29, 2011
Dynamically generate a <li>?
Question by jimmy_in
<span id="n-email" class="email-btn"><a href="#."></a></span>
On clicking this, a list item with a text field shows
<li id="new" class="select">
<a>
<input type="text" id="emails" class="add-email" value="Untitled" onfocus="if(this.value=='Untitled'){this.value=''}" onblur="if(this.value=='') {this.value='Untitled'}"/>
</a>
</li>
Suppose I filled something in this input field and press enter.
On pressing enter I want to fire a event which would
- Remove the
<li>
containing the input field. -
Insert new
<li>
in its place, like<li> <a href="#."> //here comes the value what we entered in the input field of above li// </a> </li>
Answer by Starx
First, you need to hide the #new
row, then you need to use keypress
event to catch the enter key, finally use the append()
method to insert a new element.
Here is a example based on your script
$(".email-btn").click(function() {
$("#new").show();
});
$("#emails").keypress(function(e)
{
value = $(this).val();
code= (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$("#new").remove();
$("#mylist").append("<li><a>"+value+"</a></li>");
}
});