Home > Back-end >  How to check checkboxs based on text string HTML/JS
How to check checkboxs based on text string HTML/JS

Time:08-09

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 ><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
<label ><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
<label ><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>

(JSFiddle)

CodePudding user response:

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 ><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
<label ><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
<label ><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>

CodePudding user response:

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 ><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
<label ><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
<label ><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>

  • Related