Reputation: 54949
I have the following HTML Structure
<form action="todo.php" method="post" name="todo">
<ul>
<li>
<input name="checklist[0]" type="text">
<ul>
<li>
<input name="checklist[0][task][]" type="text">
</li>
<li>
<input name="checklist[0][task][]" type="text">
</li>
</ul>
<a class="add" href="todo.php">Add one</a> </li>
<li>
<input name="checklist[1]" type="text">
<ul>
<li>
<input name="checklist[1][task][]" type="text">
</li>
<li>
<input name="checklist[1][task][]" type="text">
</li>
<li>
<input name="checklist[1][task][]" type="text">
</li>
</ul>
<a class="add" href="todo.php">Add one</a> </li>
<li>
<input name="checklist[2]" type="text">
<ul>
</ul>
<a class="add" href="todo.php">Add one</a> </li>
</ul>
<input name="submit" type="submit" value="Submit">
</form>
jQuery Code
$( ".add" ).click(function() {
// Find the Task Count
var task_count = $(this).siblings('ul').children('li').length;
var task_name = $(this).siblings('ul').children('li').attr("name");
var input = '<li><input name="checklist[][task][]" type="text"></li>';
console.log(task_count);
console.log(task_name);
$(this).siblings('ul').append(input);
return false;
});
When i click Add i want to get the Sibilling UL
's first Child's NAME
Attribute
In the Above code's
var task_name = $(this).siblings('ul').children('li').attr("name");
This seems to throw back undefined
Upvotes: 0
Views: 179
Reputation: 1287
$(this).siblings('ul').children('li').attr("name")
This will throw undefined
as li
elements are not having any name
attribute
you need to do ths :-
$(this).siblings('ul').children('li').find('input').attr("name")
OR
$(this).siblings('ul').children('li').children('input').attr("name")
Upvotes: 1
Reputation: 2574
Try:
var task_name = $(this).parents("li:first").find("input[name]:first").attr('name');
Upvotes: 1
Reputation: 28513
try this : You are trying to get name
attribute of li
, instead find input
inside li
and then get its name
attribute
var task_name = $(this).siblings('ul').children('li:first').find('input').attr("name");
Upvotes: 1
Reputation: 67207
The way that you are trying to do the dom manipulation
is wrong. You are actually targeting the li
element in your code, but the requirement is to grab the input
element present inside of that li
. So you should use .find()
to search for the descendants inside of that li
.
Try,
var task_name = $(this).siblings('ul').children('li:first').find("input").attr('name');
Upvotes: 0