-1

I meet some trouble on how can i display the name call from ajax when checkbox is selected ?

This is image below where my ajax is call to create a checkbox for each of them enter image description here

Now i would like that when i select any checkbox given the name will be display below the Selected: and if i unselect the checkbox the name will disappear how can i do it as i am using ajax to call ?

Here my html code

                                <div class="container-body ">
                                <fieldset class="Field">
                                <ul id="checkbox" class="checkbox">
                                </fieldset>
                                </ul>
                                <div id="no-recyclable-records" >
                                    <h4>No Recyclable Records Found</h4>
                                </div>
                            </div>

                        <div class="Select">
                        <p>Selected:</p>
                        <div id="divfilter"></div>
                        </div>

This is my ajax code that i am using to create my checkbox:

$.ajax( {
            url: 'https://ecoexchange.dscloud.me:8090/api/get',
            type: 'GET',
            dataType: 'json',
            headers:{
                query: "RecyclableGet(0)",
                // Gets the apikey from the sessionStorage
                apikey: sessionStorage.getItem("apikey")
            },
            success: function(data) {
            //console.log(data);
            var html='';
            $.each(data, function(key, value) {
                var type = value.RecyclableType
                //console.log(type)
                html +='<li data-type="'+ type + '"><input type="checkbox" name="recyclable_id[]" value="'+value.RecyclableID+'"><label style="padding-left: 10px;">'+value.Name+'</label><br></li>';
                //console.log(value)
            });
            $('#checkbox').html(html);
            // Toggled it to success after loading all of the checkboxes
            // This will hide the "No Recyclable Records" portion
            toggleRecord("success");



            }
        });

I try to use a javascript but no name is display

// find and retrieve all <input> elements of
    // 'type=checkbox':
    var checkboxes = $('input[type=checkbox]');

    // use the on() method to bind the anonymous function
    // as the event-handler of the 'change' event:
    checkboxes.on('change', function(){

    // update the '#divfilter' element's text:
    $('#divfilter').text(function(){

        // we return the following as the new text:

        // first we filter the checkboxes collection to
        // retain only those that match the ':checked'
        // pseudo-class, and then create a map:
        return checkboxes.filter(':checked').map(function(){

        // the contents of the map are comprised of
        // the 'name' property of each checked check-box:
        return value.Name;
        //return this.name;

        // we convert the map() into an Array, using get():
        }).get()

        // and join the Array elements together with the
        // supplied String, and finished with a period:
        .join(', ') + '.';
    });
    });
Flow
  • 271
  • 2
  • 11
  • What is `value` in `value.Name`? – Barmar Dec 30 '21 at 17:37
  • it suppose to be my value. name = to my ajax name – Flow Dec 30 '21 at 17:38
  • supply an argument to the function in `.map(function(){` such as `.map(function(n){` and access properties of `n` within the anonymous function – Professor Abronsius Dec 30 '21 at 17:41
  • It looks like you are appending `li` elements directly into a `div` with no suitable `list` parent or have I missed that? – Professor Abronsius Dec 30 '21 at 17:45
  • i have cut some of the code as the code is for my drop down list with the toggle record on when item there is none it display – Flow Dec 30 '21 at 17:48
  • Selectors and event handlers specified at page load will only match elements which exist at page load. You are adding new elements *after* page load, and your event listeners will not match them - jQuery doesn't know about those new elements. You need to delegate your handlers to an element that exists at load, and filter to match only your target elements. See https://stackoverflow.com/questions/1359018/how-do-i-attach-events-to-dynamic-html-elements-with-jquery and https://api.jquery.com/on/#direct-and-delegated-events – Don't Panic Dec 30 '21 at 22:41
  • In your case, change your event handler to something like `$('#checkbox').on('change', '[type=checkbox]', function(){` - so the handler is bound to an element which exists at page load. – Don't Panic Dec 30 '21 at 22:45
  • Note you also have broken HTML - the `
      ` and `
      ` tags are overlapping.
    – Don't Panic Dec 30 '21 at 22:48
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Don't Panic Dec 30 '21 at 22:49

1 Answers1

0

As I'm not a user of jQuery I cannot adequately suggest the means to do this with jQuery but the following, using vanilla javascript, might give an idea how you can display the name/value of any selected checkbox from those found on the page.

const changehandler = function(e) {
  let div=document.getElementById('divfilter');
      div.textContent='';

  let col = document.querySelectorAll('input[type="checkbox"]:checked');
  let text = [...col].map(n => [n.parentNode.dataset.type,n.value].join('=')).join(',');

  if (text != '') {
    div.textContent=text;
  }
};


document.querySelectorAll('input[type="checkbox"]').forEach(n => n.addEventListener('change', changehandler))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='divfilter'></div>


<ul>
  <li data-type="Banana">
    <input type="checkbox" name="recyclable_id[]" value="yellow" />
    <label>Banana</label>
    <br>
  </li>

  <li data-type="Apple">
    <input type="checkbox" name="recyclable_id[]" value="Green" />
    <label>Apple</label>
    <br>
  </li>

  <li data-type="Cherry">
    <input type="checkbox" name="recyclable_id[]" value="Red" />
    <label>Cherry</label>
    <br>
  </li>
</ul>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46