Josh
Josh

Reputation: 13

jQuery selecting list items

I'm having trouble seeing what's wrong with my code. I'm trying to select my list items, but they don't seem to get selected.

Here's my HTML

    <!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Tasklistr</title>
    <style type="text/css"> @import url(styles.css);</style>
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js'></script>
    <script type="text/javascript" src="application.js"></script>
</head>

<body>
  <h1>JSTasker</h1>

  <form>
    <fieldset>
      <legend>Add a Task</legend>
      <input type='text' name='task_text' id='task_text' />
      <input type='submit' name='add_button' value='Add' id='add_button' />
    </fieldset>
  </form>

  <div id='tasks'>
      <h2>Your Tasks </h2>
      <ul>
      </ul>
  </div>
</body>
</html>

My application.js

$(document).ready(function() {
    $('input#add_button').click(function(event) {
        event.preventDefault();
        var task_text = $('input#task_text').val();
        var task_item = "<li><p>" + task_text + "</p></li>"
        $('div#tasks ul').append(task_item);
        $('input#task_text').val(null);
    });

    $('input#task_text').focus();

    $('div#tasks ul li').click(function() {
        alert("Hey");
    });



});

Upvotes: 1

Views: 2595

Answers (1)

Aron Rotteveel
Aron Rotteveel

Reputation: 83223

You should use .live() instead of .click().

You are currently binding a click event to DOM-elements that don't exist at the time of binding (since you are adding them by clicking the button). live() solves this problem: events bound by this method also work for elements that are created after live() is called.

Example:

$('div#tasks ul li').live('click', function(){
    alert("Hey");
});

Upvotes: 3

Related Questions