Home > Blockchain >  JQuery select list item
JQuery select list item

Time:12-14

I want to select an item from a list once it is clicked ive tried appending classes and things like that but the click event doesnt seem to recognise the list items, the items also need be able to be deleted later so i think giving them classes is the best option for this scenario here is my code:

function newElement() {
  $(document).ready(function() {
    $("UL").append($("<li>").html($("input").val()).addClass("Item"));
  });

};

$(".item").click(function() {
  var $items = $('li'),
    $selected = $items.filter('.selected').removeClass('selected'),
    $next;
  // first time only when no selected exists, remove if you automatically select first one
  if (!$selected.length) {
    $next = $items.first();
  } else {
    $next = $selected.is($items.last()) ? $items.first() : $selected.next();
  }

  $next.addClass('selected')

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="div1" >
  <input type="text" id="input" placeholder="...">
  <span onclick="newElement()" >Add</span>
</div>

<ul id="UL" >
  <li >blank 1</li>
  <li >blank 2</li>
  <li >blank 3</li>
</ul>

CodePudding user response:

If i understood your question that the next <li> must get the selected class.

Then its achievable using your code with slight changes.

Fist add a data-key

<ul id="UL" >
    <li data-key='0' >blank 1</li>
    <li data-key='1' >blank 2</li>
    <li data-key='2' >blank 3</li>
</ul>

Then use that marker for the click event

$(".item").click(function() {
    var $items = $('li'), $next;
    var target = $(this).data('key')   1 ;
    $items.removeClass('selected')
    if (target >= $items.length) {
        $next = $items[0];
    } else {
        $next = $items[target];
    }
    $next.classList.add('selected');
});

CodePudding user response:

If your question is that how to add list item dynamically and assign an eventHandler for click on them, you can do it like this: (in below example I just toggle the selected class)

function newElement() {
  $("#UL").append($("<li>").html($("input").val()).addClass("item"));
};

$('#UL').on('click', '.item', function() {
  const target = $(this);
  const shouldSelect = !target.hasClass('selected');

  $('#UL li.selected').removeClass('selected');
  shouldSelect && target.addClass('selected');
});
.selected {
  background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

<div id="div1" >
  <input type="text" id="input" placeholder="...">
  <span onclick="newElement()" >Add</span>
</div>
<ul id="UL" >
  <li >blank 1</li>
  <li >blank 2</li>
  <li >blank 3</li>
</ul>

CodePudding user response:

Your question was slightly unclear regarding the "select" SO I simply made an assumption you wanted to do something with a selected element - like remove it; so I added an example of that functionality.

Some comments regarding code

  • Did not need to put the append inside a document ready event handler
  • Used the wrong class Item vs item
  • I cloned the first one when we start here to use in case all the li get deleted, otherwise I clone the first one when you "add" to allow more modular code - like if you end up with more "inside" your li like a span or some such - easier to "modify it" than "create it there with complex markup addition(s).
  • using 'UL' as a selector is often not a great choice so I gave the ul an ID
  • cached the $myList to make a refactor easier for that new ul id
  • added a button to trigger a delete of the selected li - if you need it for some other reason you can refactor from that.

// save a cloned item to add when we remove them all
let clonedItemSave = $('#my-ul-list').find('.item').first().clone(true, true);
let $myList = $('#my-ul-list');

function newElement(event) {
  let clonedItem =
    (!!$myList.find('.item').length) ?
    $myList.find('.item').first().clone(true, true) : clonedItemSave;
  let addInput = $("#add-item-input").val();
  //insert new clone of item if we have an input value:
  if (addInput != "") {
    clonedItem.html($("input").val()).appendTo("#my-ul-list");
  }
}
// scope to the UL since any might be removed later per question statement
// gave the ul an id so we can target it specifically
$myList.on('click', '.item', function(event) {
    // delegateTarget is the UL here
    let $items = $(event.delegateTarget).find('li');
    $items.filter('.selected').not(this).removeClass('selected');
    $selected = $items.filter('.selected').not(this).removeClass('selected');
    $selected = $('.selected');
    if (!!$selected.length) {
      $selected.toggleClass("selected")
    } else {
      $(this).addClass('selected');
    }
  })
  // handle the remove
  .on('remove-selected', function() {
    $(this).find('.selected').remove();
  });
$('#add-button').on('click', newElement);
$('#remove-selected').on('click', function(even) {
  //trigger the remove
  $myList.trigger('remove-selected');
});
.selected {
  background-color: #ffff00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div >
  <input type="text" id="add-item-input" placeholder="...">
  <button type="button"  id="add-button">Add</button>
</div>

<ul id="my-ul-list" >
  <li >blank 1</li>
  <li >blank 2</li>
  <li >blank 3</li>
</ul>
<button type="button" id="remove-selected">Remove Selected</button>

  • Related