Skip to content Skip to sidebar Skip to footer

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 (

Solution 1:

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

Solution 2:

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.

enter image description here

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

Solution 3:

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;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script><div><ul><li><span>Example 1</span><inputtype='hidden'value='0'></li><li><span>Example 2</span><inputtype='hidden'value='1'></li><li><span>Example 3</span><inputtype='hidden'value='2'></li></ul></div><h4></h4>

Post a Comment for "Assign A Index Value To The List Element Value Dynamically In Sortable Jquery"