Reputation: 2800
I have a view which displays a couple of divs
. These divs
are sortable/draggable using jquery-ui's sortable widget.
I am trying to update the value of an input field based on the position of the div. However, I only got this far: I am updating the html
of whole div
instead of updating value
of the containing input field. Which would be the best selector to use to update the value
of input fields instead of the the entire div's html?
HTML
<div id="sortable" class="ui-sortable">
<div class="ui-state-default">0<input id="sort_order_1" name="sort_order[]" type=text value="0"></div>
<div class="ui-state-default">1<input id="sort_order_2" name="sort_order[]" type=text value="1"></div>
<div class="ui-state-default">2<input id="sort_order_3" name="sort_order[]" type=text value="2"></div>
<div class="ui-state-default">3<input id="sort_order_4" name="sort_order[]" type=text value="3"></div>
<div class="ui-state-default">4<input id="sort_order_5" name="sort_order[]" type=text value="4"></div>
<div class="ui-state-default">5<input id="sort_order_6" name="sort_order[]" type=text value="5"></div>
<div class="ui-state-default">6<input id="sort_order_7" name="sort_order[]" type=text value="6"></div>
</div>
JavaScript
$(function() {
$('#sortable').sortable({
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
change: function(event, ui) {
var start_pos = ui.item.data('start_pos');
var index = ui.placeholder.index();
cIndex = (start_pos < index) ? index - 2 : index - 1;
ui.placeholder.prevAll('div').each(function() {
$this = $(this);
if ($this.is(ui.item)) {
return;
}
$this.html(cIndex);
cIndex--;
});
cIndex = (start_pos < index) ? index : index + 1;
ui.placeholder.nextAll('div').each(function() {
$this = $(this);
if ($this.is(ui.item)) return;
$this.html(cIndex)
cIndex++;
});
ui.item.html((start_pos < index) ? index - 1 : index);
},
axis: 'y'
});
});
I found these examples on stackoverflow, but they are not updating any input field values either.
Upvotes: 0
Views: 205
Reputation: 930
All you have to do is add the val()
update inside the each functions. I commented out the .html();
functions because they would delete your input fields.
Prev:
ui.placeholder.prevAll('div').each(function() {
$this = $(this);
if ($this.is(ui.item)) {
return;
}
//$this.html(cIndex);
$this.find('input[type=text]').val(cIndex);
cIndex--;
});
Next:
ui.placeholder.nextAll('div').each(function() {
$this = $(this);
if ($this.is(ui.item)) return;
//$this.html(cIndex);
$this.find('input[type=text]').val(cIndex);
cIndex++;
});
Sorter:
//ui.item.html((start_pos < index) ? index - 1 : index);
ui.item.find('input[type=text]').val((start_pos < index) ? index - 1 : index);
Upvotes: 1