Sandeep sandy Sandeep sandy - 9 months ago 45
HTML Question

How to use Jquery filter?


<div class="searchChkBoxDiv"><input id="searchchk_input"></div>
<div class="searchElemDiv"></div>


var checkBoxVals = ["sandeep", "suresh", "rajesh", "ramesh", "pad"];
for(var i = 0; i<checkBoxVals.length; i++){
$('.searchElemDiv').append('<div id='+checkBoxVals[i]+'><input type="checkbox"><span>'+checkBoxVals[i]+'</span></div>');

I have the above code, i would like to filter the elements in searchElemDiv added by java script.

I tried as below, but getting failed to capture the elements which were filtered by filter in array.

var val = $(this).val();
var opt = checkBoxVals.filter(function(idx, el) {
return val === '' || el.indexOf(val) == 0;
for(var i=0; i<opt.length; i++){
$('.searchElemDiv').append('<div id='+opt[i]+'><input type="checkbox"><span>'+opt[i]+'</span></div>');

When I give a first key it is removing all the elements from searchElemDiv div, and when delete entire input from input box again searchElemDiv is filled with all the elements as page loads but in between single character also not working.

Can you please help me how to figure it out.


The callback for filter return three parameters :

// the first is for the value the second for the index
function callbackfn(value, index, array1)

Take a look here :

A little example :

var checkBoxVals = ["sandeep", "suresh", "rajesh", "ramesh", "pad"];

var opt = checkBoxVals.filter(function(el, idx, array) {
  console.log("index :"+idx);
  console.log("element :"+el);
  console.log("the full array :"+array);
<script src=""></script>