skip to Main Content

Is it possible to check checkbox based on string text using js or jQuery:

$(':checkbox').filter(function() {
  return $(this).parent().next('label').text() === 'Text 1';
}).prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="selectit"><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
<label class="selectit"><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
<label class="selectit"><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>

(JSFiddle)

2

Answers


  1. Your code is almost there, you just need to remove next('label') as parent() already gives you a reference to the label.

    Also note that you can make the code a little more succinct with an arrow function:

    $(':checkbox').filter((i, el) => $(el).parent().text().trim() === 'Text 1').prop('checked', true);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <label class="selectit"><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
    <label class="selectit"><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
    <label class="selectit"><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>
    Login or Signup to reply.
  2. A JS example. It grabs the labels, finds the label with the text you pass in as an argument to the function, and if that label is found checks it’s corresponding checkbox.

    function checkBoxFromLabelText(str) {
    
      // Select all the labels and coerce the array-like node-list
      // into an array
      const labels = [...document.querySelectorAll('label')];
    
      // `find` the label with the text content you supplied
      // as a string argument to the function
      const label = labels.find(label => label.textContent.trim() === str);
    
      // If it exists find the label's checkbox and check it
      if (label) label.querySelector('[type="checkbox"]').checked = true;
    
    }
    
    checkBoxFromLabelText('Text 1');
    <label class="selectit"><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
    <label class="selectit"><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
    <label class="selectit"><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search