简体   繁体   中英

Assign a index value to the list element value dynamically in sortable JQuery

I need to have sortable list where I need to set the value of every list element to its index value, for. ex. if element ex1 becomes second then I need to set a value for it of 1 (counting from 0), if element ex2 becomes third then value of 2, and so on. I'm trying to achieve that by setting value inside the update method of sortable. But every time I'm trying to do run that it is not updating the value state, it stacks on default initial value.

Here's Js fiddle you can check it (just change the order on the list and check values inside devtools, look how it stays the same).

const orderedList = $('li');

$('ul').sortable({
  update: function() {
    orderedList.each(function(idx) {
      $(this).attr("value", idx);
    })
  }
});

https://jsfiddle.net/xpvt214o/896382/

you can just update your function, basically you are defining a const value globally,so value is not updated. when you are modifying a collection.

$('li').each(function(idx){
  $(this).attr("value", idx);
})

const getValue = $('li:first-child').attr("value");
$('h4').text(getValue);

$('ul').sortable({
  update: function() {
    var _li= $('li');
    _li.removeAttr("value");
    _li.each(function(idx) {
      var currentObj=$(this);
      console.log(currentObj.text());
      $(this).attr("value", idx);
    })
  }
});

see updated code here

Your current code will update the value of the list, you can see that in the developer window. I have placed an image of the same below.

在此处输入图片说明

If you are looking for the text to change then you can use the below code instead

You can try

orderedList.each(function(idx,value) {$(this).text(idx); }) 

Fiddle

What I Know from your question, please try this code

 $('ul').sortable({ update: function() { const orderedList = $('li'); orderedList.each(function(idx) { $(this).find('span').html("Example " + (idx + 1)); }); const getValue = $('li:first-child').find('input').val(); $('h4').text(getValue); } });
 li { list-style: none; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <div> <ul> <li> <span>Example 1</span> <input type='hidden' value='0'> </li> <li> <span>Example 2</span> <input type='hidden' value='1'> </li> <li> <span>Example 3</span> <input type='hidden' value='2'> </li> </ul> </div> <h4></h4>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM