Traversing with jQuery
I have a function that adds a new unordered list item. I'd like to set one of the element's values in the newly created list item to a value that is based on a value in the list item just above the new one.
For instance, if I have something like:
<form id="form" action="">
<ul id="list1" class="listing">
<li id="input1" class="item">
<input id="descr1" class="descr" type="text" value="" name="descr1" />
<input id="group1" class="group" type="text" value="" name="group1" />
<input id="order1" class="order_field" type="text" value="4" name="order1" />
<input id="row1" class="checkbox" type="checkbox" value="1" name="select_row1" />
</li>
<li id="input2" class="item">
<input id="descr2" class="descr" type="text" value="" name="descr2" />
<input id="group2" class="group" type="text" value="" name="group2" />
<input id="order2" class="order_field" type="text" value="5" name="order2" />
<input id="row2" class="checkbox" type="checkbox" value="2" name="select_row2" />
</li>
</ul>
If I run the function that creates a new list item, I want the value in #order2 to be incremented by 1 and then the new list item (that will now have #order3) will开发者_StackOverflow中文版 be set to 6. For example, after I have created the new list item it would look like this:
<li id="input3" class="item">
<input id="descr3" class="descr" type="text" value="" name="descr3" />
<input id="group3" class="group" type="text" value="" name="group3" />
<input id="order3" class="order_field" type="text" value="6" name="order3" />
<input id="row3" class="checkbox" type="checkbox" value="3" name="select_row3" />
</li>
I need to find a way to get to the last list item and get the value for the class .order_field and then use that value (+1) when I create the new list item. My issue is I'm not sure how to put together the selector for getting to the last list item's .order_field value.
I hope that makes sense.
Thanks, Shawn
It's simply:
var value = $('#list1 li:last .order_field').val();
You also have to convert the value to a number, which you can do using parseInt
or unary +
:
var newValue = parseInt(value, 10) + 1;
// or
var newValue = +value + 1;
$("#list1 li:last input.order_field").val()
should give you the value that you're looking for.
You can retrieve the last value with this:
var last_value = $("#list1 li:last").find(".order_field").val();
What does it do?
- Selects the last li
inside #list1
ul.
- Inside it, finds the element with class order_field
and returns its value.
To increment it, just do:
var new_value = parseInt(last_value, 10) + 1;
Hope this helps. Cheers
var newValue = parseFloat($("#list1 li:last").children(".order_field").val())+1;
Working example: http://jsfiddle.net/JBhdF/2/
精彩评论