skip to Main Content

I have many checkboxes that when user checks one of them, it makes a span with ajax with ‘tag’ attribiute .

I want that when a user click in this spans again, unchecks the checked checkbox, but when I put ‘t’ var in front of value its not working, can anybody help me?

$(document).on('click', '.clear-tags', function() {
  var t = $(this).attr('tag');
  $(":checkbox[value=t]").prop("checked", "false");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tags-res">
  <span class="clear-tags" tag="wb=38"></span>
  <span class="clear-tags" tag="attr=33|998"></span>
</div>

2

Answers


  1. You are using t as a string. You have to concatenate it instead and use as a variable.

    $(document).on('click', '.clear-tags', function() {
      var t = $(this).attr('tag');
      $(`:checkbox[value="${t}"]`).prop("checked", "false");
    });
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="tags-res">
      <span class="clear-tags" tag="wb=38"></span>
      <span class="clear-tags" tag="attr=33|998"></span>
    </div>
    
    Login or Signup to reply.
  2. You are not using t as a variable. Also you need to quote the value of the attribute to use in a selector when it has special characters in the selector.

    You may even have to escape some characters using CSS-Escape

    Here I toggle the checkbox on click of the span and quote it using template literals

    $(document).on('click', '.clear-tags', function() {
      const t = $(this).attr('tag');
      const $chk = $(`:checkbox[value="${t}"]`);
      $chk.prop("checked", !$chk.prop("checked"));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="tags-res">
      <span class="clear-tags" tag="wb=38">wb=38</span>
      <span class="clear-tags" tag="attr=33|998">attr=33|998</span>
    </div>
    
    <input type="checkbox" value="wb=38" />
    <input type="checkbox" value="attr=33|998" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search