Aaron C Velazquez Aaron C Velazquez - 2 months ago 9
CSS Question

String to array, then select check boxes

I have a jquery question. I currently store some data in a mysql table which is delimited by commas. Here is an example of the data stored


Tbl_stage " concept , prerevenue , 10mm , 20mm "


Once I echo this data in php, I need each check box to be checked if it is contained in the array

<label><input type="checkbox" id="check-item" class="primary1" checked /> concept </label>
<label><input type="checkbox" id="check-item" class="primary1" checked /> pre-revenue </label>
<label><input type="checkbox" id="check-item" class="primary1" /> sample blank data </label>


Your help is greatly appreciated!

Answer
  • First of all prepare an array without any spaces around the string.
  • Filter checkbox elements by testing text of label with array of trimmed values retrieved from DB.
  • Use jQuery.prop(PROPERTY, STATE) to set checked property.

var str = " concept , prerevenue , 10mm , 20mm ";
var arr = str.split(' , ').map(function(el) {
  return el.trim();
});
$('.primary1').filter(function() {
  return (arr.indexOf($(this).closest('label').text().replace('-', '').trim()) !== -1);
}).prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label>
  <input type="checkbox" id="check-item" class="primary1" />concept</label>
<label>
  <input type="checkbox" id="check-item" class="primary1" />pre-revenue</label>
<label>
  <input type="checkbox" id="check-item" class="primary1" />sample blank data</label>