skip to Main Content

This is the code –

<div class="filter-box" id="categoryFilter">             
    <input type="checkbox" id="3" name="Education" value="3">
    <label for="Education">Education</label>
    <input type="checkbox" id="12" name="Employment" value="12">
    <label for="Employment">Employment</label>
    <input type="checkbox" id="5" name="Goods and Services" value="5">
    <label for="Goods and Services">Goods and Services</label>
</div>

I need to target the value or the ID of the checkbox clicked so I can add it to the URL string of an API call.

How can I target the checkbox so that I can write an on click event that returns the value?

4

Answers


  1. You can add an event listener on the containing <div> element for the change event. Then, you can get the value from the event’s target.

    document.querySelector('#categoryFilter').addEventListener('change', e => {
      console.log(e.target.checked, e.target.value);
    });
    <div class="filter-box" id="categoryFilter">             
        <input type="checkbox" id="3" name="Education" value="3">
        <label for="Education">Education</label>
        <input type="checkbox" id="12" name="Employment" value="12">
        <label for="Employment">Employment</label>
        <input type="checkbox" id="5" name="Goods and Services" value="5">
        <label for="Goods and Services">Goods and Services</label>
    </div>
    Login or Signup to reply.
  2. Using jQuery:

    $('#categoryFilter').on('change', 'input[type="checkbox"]', function () {
      let me = $(this);
      let checkboxName = me.attr('name');
      let checked = me.prop('checked'); // true/false
      console.log(`The checkbox ${checkboxName} was ${checked ? 'checked' : 'unchecked'}.`);
    });
    
    Login or Signup to reply.
  3. I solved it with this solution, you have to use forEach and each loop functions then applying onchange event on them to get their value and ID

    document.querySelectorAll("input[type='checkbox']").forEach(function(element){
            element.addEventListener("change",function(e){
                console.log("TARGET VALUE "+e.target.value)
                console.log("ID: "+element.getAttribute("id"))
            })
        })
    
        $("input[type='checkbox']").each(function(i,e){
            $(e).change(function(evt){
                console.log("FROM JQUERY VALUE "+$(this).val())
                console.log("FROM JQUERY ID "+$(this).prop('id'))
            })
        })
    
    Login or Signup to reply.
    • The Label’s for should match the id, not the Input’s name
    • Don’t overuse numeric IDs, there’s a great chance at some point your IDs will duplicate and collide. Rather, remove the id and for attribute and wrap your inputs into the <label>
    • Use jQuery’s "change" event function callback
    • Use .prop() to get the desired property value
    $("#categoryFilter").on("change", ":checkbox", function() {
      const name = $(this).prop("name");
      const value = $(this).prop("value");
      const checked = $(this).prop("checked");
      console.log(`${name} ${value} ${checked}`);
    });
    <div class="filter-box" id="categoryFilter">
      <label>
        <input type="checkbox" name="Education" value="3">
        Education
      </label>
      <label>
        <input type="checkbox" name="Employment" value="12">
        Employment
      </label>
      <label>
        <input type="checkbox" name="Goods and Services" value="5">
        Goods and Services
      </label>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

    With the death of IE browsers, and evergreen browsers keeping pace with the newest ECMAScript goodies, jQuery is not necessary nowadays. A pure JavaScript approach, without the overhead of a library like jQuery would be:

    document.querySelector("#categoryFilter").addEventListener("change", (evt) => {
      const el = evt.target.closest("[type=checkbox]");
      if ( !el ) return; // Not a checkbox
      console.log(`${el.name} ${el.value} ${el.checked}`);
    });
    <div class="filter-box" id="categoryFilter">
      <label>
        <input type="checkbox" name="Education" value="3">
        Education
      </label>
      <label>
        <input type="checkbox" name="Employment" value="12">
        Employment
      </label>
      <label>
        <input type="checkbox" name="Goods and Services" value="5">
        Goods and Services
      </label>
    </div>

    Notice also, the above example in pure JavaScript uses Event delegation, similar to what you would do in jQuery with $(parent).on("eventName", "dynamicChild", fn) – which will work even for dynamically created checkbox elements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search