Searching throught data-value on keyup - javascript

So, I while I type I need to show elements with certain text that is equals data-value="certain text". I've tried several ways, but nothing seems to work.
Here is what I have so far.
$(".search").keyup(function () {
var filter = $(this).val(), count = 0;
$(".element-holder .element").each(function () {
var current = $('.element').attr('data-name');
if ($(".element[data-name='" + current + "']").text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
} else {
$(this).show();
count++;
}
});
});
This is what I need help with ;l
#Edit
HTml here
<div class="element-holder ">
<div class="element" data-name='Adam' id='1'>
</div>
<div class="element" data-name='Eva' id='32'>
</div>
<div class="element" data-name='Sara' id='412'>
</div>
</div>

Please try below
$(".search").keyup(function () {
var filter = $(this).val(), count = 0;
$(".element-holder .element").each(function () {
var current = $('.element').attr('data-name');
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
} else {
$(this).show();
count++;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="search"/>
<div class="element-holder ">
<div class="element" data-name='Adam' id='1'>How to Format
</div>
<div class="element" data-name='Eva' id='32'>How to Edit
</div>
<div class="element" data-name='Sara' id='412'>Searching throught data-value on keyup
</div>
</div>

Lot of mistakes in your html .
spelling mistakes of element class used.
You did not show the search input html.
Different data attribute name.
If you are using each and make use of $(this) to select current element
Checkout my below demo
$(".search").keyup(function () {
var entered = $(this).val();
$(".elemnet").each(function () {
var text = $(this).html();
if(entered !="")
{
if(text.indexOf(entered) > -1)
{
$(this).show();
}else
{
$(this).hide();
}
}else{
$(".elemnet").hide();
}
});
});
Working Demo
Demo using data attribute

Searching through the entire DOM on each keyup is going to cause a huge performance drop. Cache your results
Throttle your keyup event to only fire the filter when the user pauses typing
Re use your regular expression instead of re creating it multiple times inside your loop
```
// Cache your elements before hand
var namedElements = $(".element-holder .element");
// inside your throttled keyup event handler
// Check for empty strings
var filter = (this.value || "").trim(),
regex = new RegExp(filter, 'i');
var toShow = namedElements.filter(function(index, element) {
var dataName = element.data("name");
return regex.test(dataName);
});
toShow.show();
var toHide = namedElements.filter(function(index, element) {
var dataName = element.data("name");
return !regex.test(dataName);
});
toHide.hide();
```

Related

How to link div visibility with input text by simple if condition statement

I want to link the visibility of two html div with whether input has value or not by very simple if condition statement but I may have problem in it.
html:
<input id="tags" />
<div id="div1" >
this is first div means input don't have value values
</div>
<div id="div2" >
this is second div means input does have value.
</div>
script:
$('#tags').on('keyup',function(e){
var div1 = $('#div1');
var div2 = $('#div2');
var txt=$(this).val ;
if (txt.length == 0){
div1.hide();
div2.show();
} else {
div1.show();
div2.hide();
}
});
It works only by the first time I type to input.
Can anyone help me please?
use this :
var txt=$(this).val() ;
instead of
var txt=$(this).val ;
Refer jQuery docs for correct usage of val() function.
Error:Invalid jquery Object change to val() instead of val .And validate the length.use with trim() for remove the unwanted space otherwise it will be count the empty spaces also
$('#tags').on('keyup', function(e) {
var div1 = $('#div1');
var div2 = $('#div2');
var txt = $(this).val().trim().length;
if (txt.length == 0) {
div1.hide();
div2.show();
} else {
div1.show();
div2.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="tags" />
<div id="div1">
this is first div means input don't have value values
</div>
<div id="div2">
this is second div means input does have value.
</div>
Use $(this).val().length
<input id="tags" />
<div id="div1" >
this is first div means input don't have value values
</div>
<div id="div2" >
this is second div means input does have value.
</div>
$('#tags').keyup(function() {
// If value is not empty
if ($(this).val().length == 0) {
div1.hide();
div2.show();
} else {
div1.show();
div2.hide();
}
}).keyup(); // Trigger the keyup event on page load
$(function(){
$('#tags').on('keyup',function(e){
var div1 = $('#div1');
var div2 = $('#div2');
var txt=$(this).val() ;
if (!txt.length){
div1.show();
div2.hide();
} else {
div1.hide();
div2.show();
}
});
});
// Declaring outside of the functions speeds up the page because it prevents
// jQuery from parsing the hole html document again.
var div1 = $('#div1');
var div2 = $('#div2');
// Declare the function outside of jQuery so that we can init the fields
function handleKeyup(event) {
var content = event.target.value;
if (content.length !== 0) {
div1.hide();
div2.show();
return;
}
div1.show();
div2.hide();
}
// Call the function with no data to init the div fields
handleKeyup({ target: { value: '' } });
// Register the keyup listener
$('#tags').on('keyup', handleKeyup);
Hope it helps. Here's a pen of the working code: https://codepen.io/flasd/pen/mMXYMa

Javascript Keyup Search of Child Div Value

I have a list of tasks that I would like to create a search function for. I have managed to have it so that as soon as you start typing, the list responds and hides all incorrect results. However I am still unable to show the correct result.
Codes are below
UPDATED WITH CORRECT SOLUTION
HTML
<input type="text" id="search" placeholder="Player Search" />
<div id="todo">
<div class="task">Task 1</div>
<div class="task">Task 2</div>
<div class="task">Task 3</div>
</div>
Javascript
var $div = $("#todo")
var result;
$("#search").keyup(function() {
var val = $.trim(this.value).toUpperCase();
if (val === "")
$(".task").show()
else {
$(".task").hide()
result = $("#todo .task").filter(function() { //Updated to match child of id todo
return -1 != $(this).text().toUpperCase().indexOf(val)
}).show()
console.log(result)
$(".task").eq(result).show();
}
})
As I have only started learning javascript, I would appreciate if you could explain my errors, and a laymen step-by-step explanation of the answer/process.
As a bonus, if you could also explain how one would troubleshoot a javascript problem like this to find the underlying problem, that would be appreciated.
var $div = $("#todo")
var result;
$("#search").keyup(function() {
var val = $.trim(this.value).toUpperCase();
if (val === "")
$div.show()
else {
$(".task").hide()
result = $("#todo .task").filter(function() { //Updated to match child of id todo
return -1 != $(this).text().toUpperCase().indexOf(val)
}).index()//get the index of the div that has match
console.log(result)
result != -1 ? $(".task").eq(result).show() : $(".task").hide()//show or hide div depending on matching index
}
})
DEMO
Always remember ID should always be unique in same context.
Use class to target multiple elements.
function SearchContactInGroup(Strtext) {
$('#userchat_grouping .name').each(function () {
if ($(this).text().toLowerCase().indexOf(Strtext.toLowerCase())>= 0) {
$(this).closest('li').show('slow');
}
else {
$(this).closest('li').hide('slow');
}
});
// $('#dvLoading').hide();
}
$(window).load(function () {
$('#txtsearch').keyup(function () {
SearchContactInGroup($(this).val());
});});

jquery ignoring upper&lowercase in function

hello world i have an problem i am currently making experimental search boxes with divs for my homepage ..
now ive tried to ignore the upperand lowercase but nothing will going successfull so i will ask how i can get ignore the upper and lower case in my code:
$(window).load(function(){
function hide_divs(search) {
if(search === "") {
$("#sboxs > div").show();
} else {
$("#sboxs > div").hide(); // hide all divs
$('#sboxs > div[id*="'+search+'"]').show(); // show the ones that match
}
}
$(document).ready(function() {
$("#search_field").keyup(function() {
var search = $.trim(this.value);
hide_divs(search);
});
});
});
html:
<div id="jOhAnNeS">heres the content of(Johannes)</div>
<div id="michael">heres the content of(Michael)</div>
<div id="TOM">heres the content(Tom)</div>
<div id="JERry">heres the content(Jerry)</div>
<div id="kIM">heres the content(Kim)</div>
<div id="joschUA">heres the content(Joschua)</div>
<div id="katY">heres the content(Katy)</div>
</div>
try this function instead
function hide_divs(search) {
var divs = $("#sboxs > div");
var match = search.toLowerCase();
divs.each( function(i,elem) {
if ( elem.id.toLowerCase().indexOf(match) > -1 )
$(elem).show();
else
$(elem).hide();
});
}

Jquery - text filter to hide divs

I'm trying to use jquery to to create a live filter to hide divs on realtime text input. So far I have the following:
<input type="text" class="form-control" id="filter" name="filter" class="filter">
<div class="media">
<div class="media-body>
<h4>Apples</h4>
...
</div>
</div>
<div class="media">
<div class="media-body>
<h4>Oranges</h4>
...
</div>
</div>
<script>
$('#filter').keyup(function () {
var filter = $("#filter").val();
$('.media').each(function(i, obj) {
if ($('this > .media-body > h4:contains(filter)').length === 0) {
$(this).css("display","none");
}
});
});
</script>
I want this to work so that as soon as someone types an 'o' the apples div is hidden but currently it hides all the divs as soon as anything is typed.
Also how can I make it case insensitive?
Big thanks to everyone who responded to this question - in the end I went with the solution Fabrizio Calderan provided, but have made a few modifications to it that allow for the text filter to search a string for words in any order and to redisplay previously hidden divs if the user deletes what they've typed, I thought I would share this modified solution with you:
$('#filter').keyup(function () {
var filter_array = new Array();
var filter = this.value.toLowerCase(); // no need to call jQuery here
filter_array = filter.split(' '); // split the user input at the spaces
var arrayLength = filter_array.length; // Get the length of the filter array
$('.media').each(function() {
/* cache a reference to the current .media (you're using it twice) */
var _this = $(this);
var title = _this.find('h4').text().toLowerCase();
/*
title and filter are normalized in lowerCase letters
for a case insensitive search
*/
var hidden = 0; // Set a flag to see if a div was hidden
// Loop through all the words in the array and hide the div if found
for (var i = 0; i < arrayLength; i++) {
if (title.indexOf(filter_array[i]) < 0) {
_this.hide();
hidden = 1;
}
}
// If the flag hasn't been tripped show the div
if (hidden == 0) {
_this.show();
}
});
});
You need to properly interpolate the selector string with the actual value of filter.
You also have a typo in $('this > ....
Try this code (with some improvements)
$('#filter').keyup(function () {
var filter = this.value.toLowerCase(); // no need to call jQuery here
$('.media').each(function() {
/* cache a reference to the current .media (you're using it twice) */
var _this = $(this);
var title = _this.find('h4').text().toLowerCase();
/*
title and filter are normalized in lowerCase letters
for a case insensitive search
*/
if (title.indexOf(filter) < 0) {
_this.hide();
}
});
});
Try
if (!RegExp.escape) {
RegExp.escape = function (value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
var $medias = $('.media'),
$h4s = $medias.find('> .media-body > h4');
$('#filter').keyup(function () {
var filter = this.value,
regex;
if (filter) {
regex = new RegExp(RegExp.escape(this.value), 'i')
var $found = $h4s.filter(function () {
return regex.test($(this).text())
}).closest('.media').show();
$medias.not($found).hide()
} else {
$medias.show();
}
});
Demo: Fiddle
Modified the answer to this
var filter = this.value.toLowerCase(); // no need to call jQuery here
$('.device').each(function() {
/* cache a reference to the current .device (you're using it twice) */
var _this = $(this);
var title = _this.find('h3').text().toLowerCase();
/*
title and filter are normalized in lowerCase letters
for a case insensitive search
*/
if (title.indexOf(filter) < 0) {
_this.hide();
}
else if(filter == ""){
_this.show();
}
else{
_this.show();
}
});
});
Try this -
if ($('.media-body > h4:contains('+filter+')',this).length === 0) {
$(this).css("display","none");
}
This is wrong:
if ($('this > .media-body > h4:contains(filter)').length === 0) {
You should do like this:
if ($(this).find(' > .media-body > h4:contains('+filter+')').length === 0) {
Or like this:
if ($(' > .media-body > h4:contains('+filter+')', this).length === 0) {
You need to use .children() as well as concatenate your filter variable using +, so use:
if ($(this).children('.media-body > h4:contains(' + filter +')').length === 0) {
$(this).css("display","none");
}
instead of:
if ($('this > .media-body > h4:contains(filter)').length === 0) {
$(this).css("display","none");
}
example here
$('#filter').keyup(function () {
var filter = $("#filter").val();
$('.media').each(function() {
$(this).find("h4:not(:contains('" + filter + "'))").hide();
$(this).find("h4:contains('" + filter + "')").show();
});
});
You can simplify this code to:
$('#filter').keyup(function () {
// create a pattern to match against, in this one
// we're only matching words which start with the
// value in #filter, case-insensitive
var pattern = new RegExp('^' + this.value.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'i');
// hide all h4's within div.media, then filter
$('div.media h4').hide().filter(function() {
// only return h4's which match our pattern
return !!$(this).text().match(pattern);
}).show(); // show h4's which matched the pattern
});
Here's a fiddle
Credit to this answer for the expression to escape special characters in the value.
You can use this code.
$('#filter').keyup(function () {
var filter = this.value.toLowerCase();
$('.media').each(function () {
var _this = $(this);
var title = _this.find('h1').text().toLowerCase();
if (title.indexOf(filter) < 0) {
_this.hide();
}
if (title.indexOf(filter) == 0) {
_this.show();
}
});
});

Detect user selection within html element

How can I detect if a user selection (highlighting with mouse) is within/a child of a certain element?
Example:
<div id="parent">
sdfsdf
<div id="container">
some
<span>content</span>
</div>
sdfsd
</div>
pseudo code:
if window.getSelection().getRangeAt(0) is a child of #container
return true;
else
return false;
Using jQuery on() event handler
$(function() {
$("#container > * ").on("click",
function(event){
return true;
});
});​
Edit: http://jsfiddle.net/9DMaG/1/
<div id="parent">outside
<div id="container">
outside
<span>first_span_clickMe</span>
<span>second_span_clickMe</span>
</div>
outside</div>
$(function() {
$("#container > span").on("click", function(){
$('body').append("<br/>child clicked");
});
});​
​
Ok I managed to solve this in a "dirty" way. The code could use improvement but it did the job for me and I am lazy to change it now. Basically I loop through the object of the selection checking if at some point it reaches an element with the specified class.
var inArticle = false;
// The class you want to check:
var parentClass = "g-body";
function checkParent(e){
if(e.parentElement && e.parentElement != $('body')){
if ($(e).hasClass(parentClass)) {
inArticle = true;
return true;
}else{
checkParent(e.parentElement);
}
}else{
return false;
}
}
$(document).on('mouseup', function(){
// Check if there is a selection
if(window.getSelection().type != "None"){
// Check if the selection is collapsed
if (!window.getSelection().getRangeAt(0).collapsed) {
inArticle = false;
// Check if selection has parent
if (window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement) {
// Pass the parent for checking
checkParent(window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement);
};
if (inArticle === true) {
// If in element do something
alert("You have selected something in the target element");
}
};
}
});
JSFiddle

Categories

Resources