Search for Text inside div - javascript

The problem is: I have one div that wraps all my users list. I want to make a search box, but i don't want to use Ajax, so i started trying JQuery, for search the text inside the div and hide the another results. I've tried but i'm stucked on this:
//Search Box
$(document).on('input', "#search-weeazer", function(e){
console.log('input ativado')
if($(this).val().length >= 4){
// if($('#colmeia-chat').html().indexOf($(this).val()) > -1){
// console.log('Found')
// } else {
// console.log('Not Found')
// }
$('div.chat-users>div').each(function(i,div){
if($(div).html().indexOf($(div).val()) > -1){
console.log($(div).html() + ' found: ' + i);
} else {
console.log("Not Found")
}
});
}
});
Someone know how i can do this?
Thanks!
In my HTML i have this:
<div class="chat-users" style="height: 400px;">
<?php include_once('user-chat-list.php'); ?>
</div>
Inside "chat-users" i have a list with all users, loaded with php
Here is more HTMl to show the structure:
https://jsfiddle.net/jdqbnz2w/

After Question Edit
Here is an updated JSFiddle based on the JSFiddle you included showing how to implement the search with your particular use-case:
JSFiddle
Original Answer:
You're missing some pertinent information in your question, such as "what does the HTML look like that comes from user-chat-list.php?" And because of that it makes it hard to understand exactly how your code applies.
Nevertheless, here is a simple example upon what you have provided that you can modify that does what you are looking for. You can run the following code snippet to see a working example:
var $searchBox = $('#search-weeazer');
var $userDivs = $('.chat-users div');
$searchBox.on('input', function() {
var scope = this;
if (!scope.value || scope.value == '') {
$userDivs.show();
return;
}
$userDivs.each(function(i, div) {
var $div = $(div);
$div.toggle($div.text().toLowerCase().indexOf(scope.value.toLowerCase()) > -1);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Search:
<input id="search-weeazer">
<p>Users:</p>
<div class="chat-users">
<div>Tony</div>
<div>Amber</div>
<div>Ronald</div>
</div>

Related

$(this).hide() hides containers it shouldn't

I have this little piece of code that filters through a list of results and hides the divs that don't match. I am writing this for a PhoneGap iOS application. It works fine on Android, but on iOS for some reason it hides the entire search field as well after typing a few characters, not just the results.
Any idea why? I've stripped it down to almost only the HTML code and jQuery and it's still happening. I tried commenting out the $(this).hide(); part and it stops hiding the search field, so I assume somehow that's the culprit, but I can't figure out why or how to fix this. Been at it for 10 hours straight. Any ideas? Maybe I can target the results some other way?
$('#box_search').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis == "") {
$('#listing-results > .listing_container').show();
} else {
$('#listing-results > .listing_container').each(function() {
var text = ($(this).find('.listing_results_text_name').text() + $(this).find('.listing_results_text_name').data("alt")).toLowerCase();
if (text.indexOf(valThis) >= 0) {
$(this).show();
} else {
$(this).hide();
}
});
};
});
obviously I cant see the html but sometimes it helps to clean the code and just change the logic slightly
var box_search = function(e){
var myIndex = $(this).val();
val = (!myIndex || myIndex==='')?false:myIndex;
if(!myIndex){
$('#listing-results > .listing_container').show();
return;
}
//
$('#listing-results > .listing_container').each(function() {
var text = $(this).find('.listing_results_text_name').text() +
$(this).find('.listing_results_text_name').data("alt")
text = (!text || text==='')?false:text;
text = text.toLowerCase();
if(text.indexOf(myIndex.toLowerCase()) >= 0){
$(this).show();
return;
}
$(this).hide();
});
} //end of function
$('.box_search').keyup(box_search);

Debug form local storage

I have a form (demo link below).
I've tried about 8 different methods of storing the data but it won't work.
(link retracted)
The goal is, the user visits the site and fills out the form (partially or complete). They can then login if they wish.
The next time they visit the site the form should be complete (excluding password) and the avatar should display with the one stored in local storage.
I can't figure out why nothing will display, whether it's a compatibility issue or syntax issue etc.
Problem Solved
another js script has been interfering with it causing it to fail. Resolved.
I'm not going to check your website for errors since you didn't provide any code. Instead I show you a quick and working way to save and read values from localStorage.
The values will be stored in key/value pairs while the key is the name of the input field.
HTML:
<input type="text" name="username" id="user" />
<input type="text" name="email" id="email" />
JS:
$('input').each(function() {
$(this).on('blur', function() {
localStorage.setItem($(this).attr('name'), $(this).val());
});
});
for (var i = 0; i < localStorage.length; i++){
var storageKey = localStorage.key(i),
storageValue = localStorage.getItem(storageKey);
$('input[name='+storageKey+']').val(storageValue);
}
Remeber that the for loop has to be inside of your domready function. Check the working fiddle below. Like this you have a dynamic approach for input fields - you can also do this for selects if you like to.
If you want some faster selectors you can also save the ID as key and select the input via id. Is even more dynamic.
Fiddle
Edit: As requested here is an example for checkboxes/selects. It might not be the best approach but its working.
JS:
$('.autofill').each(function () {
$(this).on('change', function () {
if ($(this).is('input')) {
if ($(this).attr('type') == 'checkbox') {
if ($(this).is(':checked')) {
localStorage.setItem($(this).attr('id'), 'checked');
} else {
localStorage.setItem($(this).attr('id'), '');
}
} else {
localStorage.setItem($(this).attr('id'), $(this).val());
}
} else if ($(this).is('select')) {
localStorage.setItem($(this).attr('id'), $(this).find('option:selected').val());
}
});
});
for (var i = 0; i < localStorage.length; i++) {
var storageKeyElement = $('#' + localStorage.key(i)),
storageKey = localStorage.key(i),
storageValue = localStorage.getItem(storageKey);
if (storageValue == 'checked') {
storageKeyElement.attr('checked', 'checked');
} else if (storageKey.indexOf('Select') > 0) {
storageKeyElement.find('option[value=' + storageValue + ']').attr('selected', 'selected');
} else {
storageKeyElement.val(storageValue);
}
}
Fiddle with Selects and Checkboxes
The problem is, you have syntax error.
Change all the mb-* variables to mb_*
For example:
var mb-username
should be
var mb_username
But you have another problems in your source code too:
<meta name="author" content="Michael Clarke"
has a missing /> closing tag.
And you have another error:
ReferenceError: applySetting is not defined
Fix these errors, and use your console to see errors.

creating simple JS with PHP

I am trying to recreate the JS below with PHP. The reason is that the numbered classes and values are actually IDs pulled from a mysql database. I have an area where say a report is creating, the code below shows and hides rules for that report. Since different reports have different rules, it shows and hides rules dependent on the grouping, determined in the code below as #rule_who.
When trying to recreate the following I was trying to use while loops however it got pretty ridiculous. Is there a more efficient way in JavaScript or AJAX to show and hide divs that would be better suited to using a large number of divs? The 2,3,4, and so on shouldn't be an incrementing number as it would rely on IDs and thus some numbers will disappear over time as reports are deleted.
Any help would be appreciated. Thanks
<script>
//<![CDATA[
$(window).load(function(){
$(".2").hide();
$(".3").hide();
$(".4").hide();
$('#rule_who').on('change', function () {
if(this.value === "2"){
$(".2").show();
$(".3").hide();
$(".4").hide();
} else if(this.value === "3"){
$(".2").hide();
$(".3").show();
$(".4").hide();
} else if(this.value === "4"){
$(".2").hide();
$(".3").hide();
$(".4").show();
} else {
$(".2").hide();
$(".3").hide();
$(".4").hide();
}
});
});//]]>
</script>
EDIT: Thanks everyone for the help.
What I ended up using was the following:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$("#rule_who").change(function() {
$("div.specific_rules").hide();
var targetId = $(this).val();
console.log($(targetId).html());
// show the new selected one
$("#"+targetId).show();
});
});//]]>
</script>
I think you can do:
$('.' + this.value).show();
$('.' + this.value).siblings().hide();
Try this (FIDDLE EXAMPLE HERE):
$('.1, .2, .3').hide();
$(window).load(function(){
$('#rule_who').on('change', function () {
var elems = document.getElementsByTagName('div');
for (var i = 0; i < elems.length; i++) {
if (elems[i].className != this.value) {
elems[i].style.display = 'none';
} else {
elems[i].style.display = 'block';
}
}
});
});

Hide text area based on selection - Jquery

Here's what I'm trying to do. When the page loads, the option "Self" will be selected and there will be no text area next to it. When the user chooses "Other" then the text area will show up next to it. Any help would be much appreciated. I've been stuck on this for a bit and I'm about to pull out what hair I have left.
Here is my code.
HTML
<select name="employee_choice" id="employee_choice" data-role="slider" data-theme="c"data-track-theme="a">
<option value="0">Self</option>
<option value="1">Other</option>
</select>
<input type="text" id="pernr" name="pernr" width="12em" />
JS
$('#employee_choice').change(function(){
var pernrField = $('#pernr');
var empSelect = $('#employee_choice').val();
pernrField.hide();
if (empSelect == '1'){
pernrField.show();
}
if (empSelect == '0'){
pernrField.hide();
}
});
Just toggle the input's visiblity based on the selects value :
$('#employee_choice').on('change', function() {
$('#pernr').toggle(this.value==='1');
});
FIDDLE
you need to check on the selected value.
var empSelect =$('select[name="employee_choice"]').val()
and instead of multiple if you can use else too
You need to run it first when the page loads. As seen in this jsFiddle, your code does work if you change the JavaScript to the following:
function showOrHidePernr() {
var pernrField = $('#pernr');
var empSelect = $('#employee_choice').val();
pernrField.hide();
if (empSelect == '1') {
pernrField.show();
}
if (empSelect == '0') {
pernrField.hide();
}
}
$('#employee_choice').change(showOrHidePernr);
$(function() {
showOrHidePernr();
});
First initialize the status, and also on the change() event:
show_pernrfield();
$('#employee_choice').change(function(){
show_pernrfield();
});
function show_pernrfield() {
var pernrField = $('#pernr');
var empSelect = $('#employee_choice').val();
if (empSelect === '1') {
pernrField.show();
}
else {
pernrField.hide();
}
}
Take a look: http://jsfiddle.net/YhaCh/1/
Try using console.log() to examine values of your variables - then it will become apparent which actions your script takes.

Disable Select based on another element on the Same Row

In a table, I have a row with two inputs - one select and one text. What I want to achieve is that if one has a value, then the other (on the same row) should disable. This works correctly onload when there is a value in the textbox, but doesn't seem to work when there is a value in only the select box.
As you can see in the example here: http://jsfiddle.net/anAgent/UBUhn/1/ the "change" event works correctly, but it doesn't work onload.
Any help would greatly be appreciated!
I'm working with jQuery 1.5.2 and with both Google Chrome and IE9
Update With Final Code
Thanks #scoopseven and #eicto for your input. Based on these two answers, here's the final code. I hope it helps someone else.
$(document).ready(function() {
$(".validation-compare").change(runRowValidation);
$(".validation-compare").each(runRowValidation);
});
function runRowValidation() {
var $me = $(this),
$other = $('.validation-compare',$me.closest("tr")).not($me),
mVal = $me.val(),
oVal =$other.val();
if(mVal != "" && oVal == "") {
$me.removeAttr('disabled');
$other.attr('disabled',1);
} else if(mVal == "" && oVal != "") {
$other.removeAttr('disabled');
$me.attr('disabled',1);
} else {
$other.removeAttr('disabled');
$me.removeAttr('disabled');
}
}​
You can see it in action at: http://jsfiddle.net/anAgent/UBUhn/24/
i don't think that you you need to set the class valid, all you have to do is replacing
var $otherInput = $('.validation-compare', $parent).not('.valid');
by
var $otherInput = $('.validation-compare', $parent).not($me);
And this will resolve your problem on onload. Here is an example
var validme=function() {
var me=$(this);
me.removeClass('validation-compare');
if (me.val()) {
console.log(me);
me.addClass('valid');
me.parent().parent().find('.validation-compare').attr('disabled',1);
me.addClass('validation-compare');
return;
}
me.removeClass('valid');
if (me.parent().parent().find('.validation-compare.valid').length<1) {
me.parent().parent().find('.validation-compare').removeAttr('disabled'); }
me.addClass('validation-compare');
}
$('.validation-compare').each(validme);
$('.validation-compare').change(validme)
http://jsfiddle.net/UBUhn/22/
You need to separate out the function and call it on the click event and on page load. Something like this:
jQuery(function($){
function myFunction() {
// do somestuff
}
// myFunction needs to be called when select is clicked and when page is loaded
$('#someelement').click(myFunction);
$(document).ready(myFunction);
});

Categories

Resources