Based in this ex. http://jsfiddle.net/vaDkF/160/ how can change input values to increase or decrease value when click on UP or DOWN mantaining order (1.2.3.4...) of values? Also how can add another button to remove row?
2 Answers
$(document).ready(function(){
$(".up,.down").click(function(){
var row = $(this).closest("tr");
if ($(this).is(".up")) {
row.prev().before(row);
} else if ($(this).is(".down")) {
row.next().after(row);
}
ResetSort();
});
$('.down').after(' <a href="#" class="delete">Delete</a>');
$('.delete').click(function() {
$(this).closest('tr').remove();
});
});
function ResetSort() {
$(':hidden[name="sort"]').each(function (i,v) {
$(v).val(i + 1);
});
}
Here is a working example: http://jsfiddle.net/JUh74/5/
UPDATE: Replaced parents('tr:first') with closest('tr'), as pointed out by fudgey
4 Comments
gonis
it seems not work as well look her and press show. always return value 1
Mottie
+1 for this more complete answer... The function you are using to "show" the input value only looks at the first input value, use this code instead
var num = $(this).closest('tr').find('input').val();. Here is an updated demo. Either way, @Shagglez has a more complete answer for you so you should accept it.Shagglez
@gonis - I'm not sure what you mean, what returns value 1? The actual solution is slightly different to what you wanted (values are forced to be the same according to their position, rather than increment/decrement) but behaviour is the same. (at)fudgey - .val() will always return the first value. I take your point about closest() (vs parents()), I wasn't aware of it earlier, but it's more efficient and better suited to current situation.
Shagglez
@gonis - oh I didn't see someone updated example - here is a working version of "show" (I didn't put it there) - jsfiddle.net/JUh74/12
Oops... I misread your question. You want to keep the "value" or the "text" in order?
Add this inside the click function:
$('input').each(function(i){
$(this).val(i+1);
});
so you end up with something like this:
$(document).ready(function(){
$(".up,.down").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
// renumber input values (not the text)
$('input').each(function(i){
$(this).val(i+1);
});
});
});
2 Comments
gonis
value order. First row must have always value 1, Second 2 ect. independently from order I make. Text go up and down but input value must have always 1.2.3 order
Mottie
The value changes, but the text of the row doesn't. I just edited my answer to add one to the value so it starts with one instead of zero.