Data attribute doesn't change value on each iteration using jQuery
When performing a list search, on each iteration the keywords are not changing. Keywords are added using data attributes in HTML Code(which is rendered from the database, so it changes li will have different keywords). So on each iteration, the keyword remains the same and the search is not working(My guess).
JS Code
function search_card() { var input, filter, txtvalue, key; input = document.getElementById('txtsearch'); filter = input.value.toLowerCase(); $('.product_card').each(function(){ key = $('.ProductNameBlock').data('keywords'); if (key.toLowerCase().indexOf(filter) > -1) { $('.product_card').css('display',''); } else { $('.product_card').css('display','none'); } }); }
keywords used
- txtsearch – input id
- product_card – li class name
- ProductNameBlock – div class name where data-keywords are rendered
(<div class="ProductNameBlock" data-keywords="<%# Eval("KeyWords")%>">
(values from db)
Keywords can be of different values for each iteration Eg: Data First, Data Collection, Featured Apps I don’t know the correct format. What do I do?
This is the correct method
function search_card() { var input, filter, txtvalue, key; input = document.getElementById('txtsearch'); filter = input.value.toLowerCase(); $('.product_card').each(function(){ key = $(this).find('.ProductNameBlock').data('keywords'); if (key.toLowerCase().indexOf(filter) > -1) { $(this).css('display',''); } else { $(this).css('display','none'); } }); }