Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does my jQuery event handler fail when attached to multiple elements?
    primarykey
    data
    text
    <p>I am using jquery to add mulitple new "addTask" form elements to a "ul" on the page every time a link is clicked. </p> <pre><code> $('span a').click(function(e){ e.preventDefault(); $('&lt;li&gt;\ &lt;ul&gt;\ &lt;li class="sTitle"&gt;&lt;input type="text" class="taskName"&gt;&lt;/li&gt;\ &lt;li&gt;&lt;input type="button" value="saveTask" class="saveTask button"&gt;&lt;/li&gt;\ &lt;/ul&gt;\ &lt;/l1&gt;') .appendTo('#toDoList'); saveTask(); }); </code></pre> <p>These new nested ul elements all have an button with the same class "saveTask". I then have a function that allows you to save a task by clicking on an button with the class "saveTask".</p> <pre><code>// Save New Task Item function saveTask() { $('.saveTask').click(function() { $this = $(this); var thisParent = $this.parent().parent() // Get the value var task = thisParent.find('input.taskName').val(); // Ajax Call var data = { sTitle: task, iTaskListID: 29 }; $.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save', data, function(data) { var newTask = '&lt;a&gt;' + task + '&lt;/a&gt;' thisParent.find('li.sTitle').html(newTask); }); return false; }); } </code></pre> <p>This essentially allows the user to enter some text into a form input, hit save, and then the task gets saved into the database using ajax, and displayed on the page using jQuery. </p> <p>This works fine when there is only one element on the page with the class "saveTask", but if I have more than 1 form element with the class "saveTask" it stops functioning correctly, as the variable "var task" shows as "undefined" rather than the actual value of the form input.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload