I have some problems when trying to get multiple fields from a jQuery form.
I use a form to create projects. The number of tasks is not predefined, so new form fields to add new tasks can be created dynamically via jQuery:
HTML FORM
<form action="#" id="createProjectForm" method="post">
<fieldset id="Project">
<label for="title">Title:</label>
<label for="title">Coordinator:</label>
<input type="text" id="coordinator" name="coordinator" placeholder="COORDINATOR" />
<div id="tasks">
<hr/>
<label for="taskTitle">Task:</label>
<input type="text" id="taskTitle" name="taskTitle" placeholder="TASK TITLE" />
</div>
<label for="createTask"></label>
<input type="button" id="createTask" value="ADD NEW TASK" />
<label for="submitTask"></label>
<input type="submit" id="submitTask" value="SAVE AND CREATE PROJECT" />
</form>
JQUERY
$("#createTask").live("click",function() {
$('#tasks').clone().insertAfter("#tasks");
});
When I clone the div "tasks", I can correctly see two "taskTitle" input fields for new tasks, but when trying to get the values (with "each"):
JQUERY
$("#createProjectForm").live("submit",function() {
var taskTitles = "";
$("#taskTitle").each(function(){
taskTitles += $.trim($(this).val()) + ",";
console.log("Task: "+taskTitles);
});
I just get the value of the first field, not the second one, like if it wasn't properly stored in the DOM...
Any suggestion? Thanks!
When you clone an item with an id the cloned item gains that same id. Jquery's id selector only selects the first match. (See here http://api.jquery.com/id-selector/)