Home > Blockchain >  Print values from selected "li" tags in JQuery
Print values from selected "li" tags in JQuery

Time:10-14

I'm new to learning about JQuery and would appreciate any assistance and guidance on how to achieve the following goal:

On my website, I have a list of selectable choices (Each selectable choice is created using <li> tags.

e.g.

<li  show-value="1">option 1</li>
<li  show-value="2">option 2</li>
<li  show-value="3">option 3</li>

I then have a div with the following structure:

<div id="shownumberlist"></div>

What I want to achieve here is to be able to show a list of all numbers that are selected (on-click) and this list needs to update if someone clicks on one of their selected choices to remove it from the list.

I want the selected number list to display in the shownumberlist div.

Thank you :-)

CodePudding user response:

Have a study of this

  1. toggle a select class on click
  2. on same click I map the li.selected in the ul
  3. fill the div with the joined array

I would personally use data-value instead of show-value since data attributes are the standard way to do this

$(function() { // on page load
  const $showList = $("#shownumberlist");
  $("#list").on("click", function(e) { // delegate from list. I could use $(".number") too 
    $(e.target).toggleClass("selected"); // something clicked
    $showList.text($(".selected", this).map(function() {  // the "this" is the UL
        return $(this).attr("show-value")
      }).get() // the array
      .join(", ") /// join with comma
    );
  })
})
#list {width: 100px; }
.selected { border: 1px solid green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<ul id="list">
  <li  show-value="1">option 1</li>
  <li  show-value="2">option 2</li>
  <li  show-value="3">option 3</li>
</ul>

<div id="shownumberlist"></div>

  • Related