Как извлечь соответствующее значение из флажка для отображения в div на основе текста поиска?

#javascript #jquery

#язык JavaScript #jquery

Вопрос:

У меня есть панель поиска, 2 дива, которые будут отображать идентификатор и фирменное наименование, и 2 флажка.

Я хочу получить данные о торговой марке в соответствии с поиском, если я найду «Nike», то идентификатор бренда и фирменное наименование divs отобразят название бренда и идентификатор на основе флажка ниже. И флажок под ним отмечен галочкой. Я кодировал, как показано ниже, но когда я отлаживаю, чтобы получить название бренда, он сливается с «nikebrand», поэтому, когда я создаю условия, это не работает

 $('.search-brand').on('keyup keypress',function(){  const brandFilterEl = $(".filter-item .filter-label")    brandFilterEl.each(function(){  const brandValues = brandFilterEl.text().toLocaleLowerCase()  console.log(brandValues)    if($('.search-brand').val() === brandValues){  const valFilterBrand = brandFilterEl.siblings().attr('value')  console.log(valFilterBrand)  $('.brand-id').text(valFilterBrand)  $('.brand-name').text(brandValues)  }  }) }); 
 lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"gt;lt;/scriptgt; lt;input type="text" class="search-brand" style="margin-bottom:20px;"gt;  lt;div class="brand-id"gt;lt;/divgt; lt;div class="brand-name"gt;lt;/divgt;  lt;li class="filter-item" style="padding-left: 20px; font-size: 12px; padding-bottom: 0; border: none;"gt;  lt;input type="checkbox" name="brandIds" value="3" style="margin-right: 5px"gt; lt;span class="filter-label"gt;Nikelt;/spangt; lt;/ligt; lt;li class="filter-item" style="padding-left: 20px; font-size: 12px; padding-bottom: 0; border: none;"gt;  lt;input type="checkbox" name="brandIds" value="2" style="margin-right: 5px"gt; lt;span class="filter-label"gt;Adidaslt;/spangt; lt;/ligt; 

Ответ №1:

Вы можете попробовать этот код, он работает так же, как и ваши ожидания.

 lt;!DOCTYPE htmlgt; lt;htmlgt; lt;headgt; lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"gt;lt;/scriptgt; lt;scriptgt; jQuery(document).ready(function($){  $('.search-brand').on('keyup keypress',function(){  const brandFilterEl = $(".filter-item .filter-label");    brandFilterEl.each(function(i){  $(this).siblings('input[name="brandIds"]').prop( "checked", false );  const brandValues = $(this).text().toLocaleLowerCase();  var search_val = $('.search-brand').val().toLocaleLowerCase();  if(search_val == brandValues){  const valFilterBrand = $(this).siblings('input[name="brandIds"]').val();  $('.brand-id').text(valFilterBrand);  $('.brand-name').text(brandValues);  $(this).siblings('input[name="brandIds"]').prop( "checked", true );  }  });  }); }); lt;/scriptgt; lt;/headgt; lt;bodygt;  lt;input type="text" class="search-brand" style="margin-bottom:20px;"gt;  lt;div class="brand-id"gt;lt;/divgt; lt;div class="brand-name"gt;lt;/divgt;  lt;li class="filter-item" style="padding-left: 20px; font-size: 12px; padding-bottom: 0; border: none;"gt;  lt;input type="checkbox" name="brandIds" value="3" style="margin-right: 5px"gt; lt;span class="filter-label"gt;Nikelt;/spangt; lt;/ligt; lt;li class="filter-item" style="padding-left: 20px; font-size: 12px; padding-bottom: 0; border: none;"gt;  lt;input type="checkbox" name="brandIds" value="2" style="margin-right: 5px"gt; lt;span class="filter-label"gt;Adidaslt;/spangt; lt;/ligt;  lt;/bodygt; lt;/htmlgt; 

Ответ №2:

Я думаю , что когда вы повторяете brandFilterEl.each , вы забываете проверить текущее значение brandFilterEl , вы можете сделать это с помощью this . Для удобства я создал псевдоним $(this) и дал ему имя $self .

 $('.search-brand').on('keyup keypress', function() {  const brandFilterEl = $(".filter-item .filter-label")   brandFilterEl.each(function() {  var $self = $(this); // this is the main change    const brandValues = $self.text().toLocaleLowerCase()   if ($('.search-brand').val() === brandValues) {  const valFilterBrand = $self.siblings().attr('value')   console.log(valFilterBrand)   $('.brand-id').text(valFilterBrand)  $('.brand-name').text(brandValues)  }  }) }); 
 lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"gt;lt;/scriptgt;  lt;input type="text" class="search-brand" style="margin-bottom:20px;"gt;  lt;div class="brand-id"gt;lt;/divgt; lt;div class="brand-name"gt;lt;/divgt;  lt;li class="filter-item" style="padding-left: 20px; font-size: 12px; padding-bottom: 0; border: none;"gt;  lt;input type="checkbox" name="brandIds" value="3" style="margin-right: 5px"gt; lt;span class="filter-label"gt;Nikelt;/spangt; lt;/ligt; lt;li class="filter-item" style="padding-left: 20px; font-size: 12px; padding-bottom: 0; border: none;"gt;  lt;input type="checkbox" name="brandIds" value="2" style="margin-right: 5px"gt; lt;span class="filter-label"gt;Adidaslt;/spangt; lt;/ligt; 

Комментарии:

1. и как также проверяется флажок? Я пробовал так $('input[name="brandIds"]').val(valFilterBrand).prop("checked", true) , но все флажки установлены