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

  1. Remove the <li> containing the input field.
  2. 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>");
    }

});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!