how to filter using jquery - javascript

html
<div class="adds">
<input type="text" value="" class="ip1" id="ip1" />
<input type="button" value="ADD" class="btn1" id="btn1" />
</br>
<div class="add">
<ul class="justList">
<li>police</li>
</ul>
</div>
</div>
<div class="filter">
<input type="text" value="" class="ip2" id="ip2" />
<input type="button" value="Filter" class="btn2" id="btn2" />
<div class="filter">
<ul>
</ul>
</div>
</div>
JS
$(document).ready(function(){
$("#btn1").on("click",function(){
var occ = $("#ip1").val();
if(occ.length)
{
$('<li />', {html: occ}).appendTo('ul.justList')
$("#ip1").val('');
}
});
});
Hi Here if i give "xxxx" and click "ADD" button the text ll append in the list of ul li, i need if i click filter i need only text that equal to what i gave second input box. it should filter all "xxxx" and it must show only that. any one help me.

See if this code works
$("#btn2").click(function () {
var value = $("#ip2").val();
$(".justList li").each(function () {
var curr_text = $(this).text();
if (curr_text == value)
console.log("equal");
else
$(this).hide();
});
});
Working Code:JSFIDDLE

You can try this using jQueries :contains selector :
$("#btn2").on("click", function () {
var occ = $("#ip2").val();
if (occ.length) {
$matches = $('.justList li:contains("'+occ+'")');
$matches.show();
$('.justList li').not($matches).hide();
}
else{
$('.justList li').show();
}
});
Demo
Update
If you want a case insensitive filter, you can create custome jQuery selector by adding the following script:
jQuery.expr[':'].Contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
and use it in the previous script.
Demo

For a filter, use jQuery filter. That is designed for this type of work.
The function passed to filter receives each element in turn and if you return true it retains it. if you return false it removes it.
Partial string matching:
It also uses match with a case-insensitive RegEx (so you can specify POL, pol or Pol and still match police in your example):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Wu2x3/2/
$("#btn2").on("click", function () {
var occ = $("#ip2").val();
var $li = $('.justList li');
if (occ.length) {
// Hide all, then show matches
$li.hide();
$li.filter(function(){
// return true if case-insensitive match occurs
return $(this).text().match(new RegExp(occ, "i"));
}).show();
}
else{
// Show everything
$li.show();
}
});
This converts the text values to lowercase before comparison to make the check case-insensitive.
*Note: These solutions will also work with strings containing quotes
Whole string matching:
If you want to match the full string only (bit odd for a filter, but as you specified):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Wu2x3/4/
$("#btn2").on("click", function () {
var occ = $("#ip2").val();
var $li = $('.justList li');
if (occ.length) {
occ = occ.toLowerCase();
// Hide all, then show matches
$li.hide();
$li.filter(function(){
// return true if case-insensitive match occurs
return $(this).text().toLowerCase() == occ;
}).show();
}
else{
// Show everything
$li.show();
}
});

Related

Problem searching for exact match from list item in JavaScript

I have the following code:
$('.lists-li').hide();
$('#search').click(function() {
$('.lists-li').hide();
var txt = $('#search-criteria').val();
$('.lists-li').each(function() {
//show match
if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
//do something
} else {
//do something
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div>
<ul class="lists-li">
<li class="lists-list"><a class="lists-li-a" href="/">David</a></li>
<li class="lists-list"><a class="lists-li-a" href="/">James</a></li>
</ul>
</div>
If I use the search box to type in 'James' I get a true match, if I type 'James2323' I get a false match which is how it should be.
The problem I am having is that if I type in 'Jam' I also get a true match but I want it to be an exact match so this should return false. Only exact matches such as 'James' or 'David' should return true.
Does anybody know how I can get the exact match only?
Thanks.
Firstly, you should correct your class name between .lists-list and .lists-li
<ul class="lists-list">
<li class="lists-li">
............
Secondly, you can compare to get exactly matching value like this
var isMached = Value == searchCriteria || searchCriteria == ""; // Assuming that empty criteria will get all items
Finally, you can use .toggle() to trigger show/hide item.
$(this).toggle(isMached);
$('#search').click(function(){
var searchCriteria = $('#search-criteria').val().toUpperCase();;
var isFound = false; // One more problem: Display "Success or Failure"
$('.lists-li').each(function(){
var tagA = $(this).find('.lists-li-a')[0];
var Value = $(tagA).text().toUpperCase();;
var isMached = Value == searchCriteria || searchCriteria == "";
$(this).toggle(isMached);
if(isMached) isFound = true; // One more problem: Display "Success or Failure"
});
$("#found-result").html(isFound ? $("#templateMessage").html() : ""); // One more problem: Display "Success or Failure"
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="search-criteria"/>
<input type="button" id="search" value="search"/>
<div id="found-result"></div>
<div id="templateMessage" style='display:none'><i>Your are here</i></div>
<div>
<ul class="lists-list">
<li class="lists-li"><a class="lists-li-a" href="/">David</a></li>
<li class="lists-li"><a class="lists-li-a" href="/">James</a></li>
</ul>
</div>

Matching input value with text inside span

I am able to match the input value with the span; however, I am only to retrieve the first span in the list I am comparing to. I need to compare to both list items. If the input is equal to either list item then it should be true. I am only getting a match for the first value.
HTML
<input id="search" type="text" class="input">
<ul> <li id="111" class="active" style="display: list-item;"><span style="display:none">111</span><span style="display: inline;">1-1-1</span></li>
<li id="222" style="display: list-item;"><span style="display:none">222</span><span style="display: inline;">2-2-2</span></li>
</ul>
JS
$('#search').on('input',function(){
if( $('#search').val() != $('ul li a span:eq(0)').text()){
return console.log('false')
}
else if( $('#search').val() == $('ul li a span:eq(0)').text()) { return console.log ('true') }
});
jsfiddle
I think that when you call .text() on a list of elements it will return the text of the first element. So you need to iterate through the spans you are interested in and check each one.
Here is an example:
$('#search').on('input',function(){
var found = false;
$('ul li a span:first-child').each(function (i, el){
if ($(el).text() == $('#search').val()) {
found = true;
return;
}
})
console.log(found);
});
Or, you could trim off all HTML tags with regex, and search the content.
function noTags(body) {
var regex = /(<([^>]+)>)/ig;
return body.replace(regex, "");
}

Multiple inputs with duplicate value check

I have a button to create input tags. When user click submit button I want to find inputs with duplicate values and change border to red.
I'm not using jquery validate plugin
html code:
<form>
<table>
<tr>
<td><input type="text" name="text[]" id="1"> <button class="add">add</button></td>
</tr>
</table>
<input type="submit" id="submit" value="check">
</form>
jQuery code:
// add input
var i = 2;
$('.add').click(function(e){
e.preventDefault();
$('table').append("<tr><td><input type="text" name="text[]" id="'+i+'"> <button class="add"></td></tr>");
i++;
});
$('#submit').click(function(){
// I do not know how to write ...
});
Here is what you want
$('#submit').click(function () {
var valid = true;
$.each($('input[type="text"]'), function (index1, item1) {
$.each($('input[type="text"]').not(this), function (index2, item2) {
if ($(item1).val() == $(item2).val()) {
$(item1).css("border-color", "red");
valid = false;
}
});
});
return valid;
});
If somebody is after this, with a lot of inputs, and is concerned with efficiency, this yields the same result (duplicates besides the first occurrence are marked):
$('#submit').click(function(){
var values = []; //list of different values
$('table input:text').each(
function() {
if (values.indexOf(this.value) >= 0) { //if this value is already in the list, marks
$(this).css("border-color", "red");
} else {
$(this).css("border-color", ""); //clears since last check
values.push(this.value); //insert new value in the list
}
}
);
});
fiddle:
https://jsfiddle.net/4s82L4vg/

Jquery Search String from span not working correctly

I am working with JQuery Filter and I am facing issue while searching string in span.
Following is the Search function which I am using:
function searchAccoms() {
var searchString = $('#searchval').val();
$('span.acc-head').each(function(){
var spanString = $(this).text();
if(spanString.search(searchString) == 1){
console.log('found');
}else{
console.log('Not Found');
}
});
}
HTML:
<input type="text" placeholder="Search" id="searchval" name="searchval">
<img src="images/icon_search.png" class="search-btn" type="submit" onclick="return searchAccoms();">
Scenario: I have following text in SPAN tag:
field
field
extra field
field1
field3
field2
Example SPAN:
<span id="18" class="acc-head"> field1</span>
When I search 'field' in the search box it works fine but when I search 'Field' the first letter in caps 'F' then it is not working. I am looking for %Field% like commend in MySQL.
Is there any other way to do the search?
Just make both strings either lowercase or uppercase to make the search case insensitive:
function searchAccoms() {
var searchString = $('#searchval').val();
$('span.acc-head').each(function(){
var spanString = $(this).text();
if (spanString.toLowerCase().search(searchString.toLowerCase()) == 1) {
console.log('found');
} else {
console.log('Not Found');
}
});
}
Another option would be to construct a regex, something like
var searchString = $('#searchval').val();
var regex = new RegExp(searchString, 'i');
...
if(spanString.search(regex) == 1)
but just making the strings the same case seems a lot easier
I guess if(spanString.match(searchString)) should do the work even if it returns an array .

jQuery live Search

I am using the method of live search with jQuery, does this code work in anyones opinion, i think there is a bug in it. It does work, although there is a bug in the code. I am using the method of live search with jQuery, does this code work in anyones opinion, i think there is a bug in it. It does work, although there is a bug in the code.
<script>
$(document).ready(function(){
$("#discount_credits").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
// Loop through the comment list
$(".commentlist li").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text("Number of meals = "+count);
});
});
</script>
<script>
$(document).ready(function(){
$("[type=range]").change(function(){
var newval=$(this).val();
$("#slidernumber").text(newval);
});
});
</script>
<div id="search_wrap">
<form id="live-search" action="" class="styled" method="post">
<fieldset>
<input type="range" min="0" step="1" max="100" name="discount_credits" id="discount_credits">
<span>£</span><span id="slidernumber">25</span>
<span id="filter-count"></span>
</fieldset>
</form>
</div>
<ul class="commentlist">
<li>22.02</li>
<li>21.99</li>
<li>21.99</li>
<li>12.00</li>
<li>42.00</li>
<li>61.99</li>
<li>2.00</li>
</ul>
The problem is in your condition. It currently does a regex match between the value in the <li> tag and the value you're putting on your range. To correct that, you should parse the content text as an int value and compare it to your filter :
// If the list item does not contain the text phrase fade it out
if (parseInt($(this).text()) > filter) {
$(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}

Categories

Resources