this is my first post on StackOverflow. I hope it doesn't go horribly wrong.
<input type="Text" id="filterTextBox" placeholder="Filter by name"/>
<script type="text/javascript" src="/resources/events.js"></script>
<script>
$("#filterTextBox").on("keyup", function () {
var search = this.value;
$(".kurssikurssi").show().filter(function () {
return $(".course", this).text().indexOf(search) < 0;
}).hide();
});
</script>
I have a javascript snippet like this on my school project, which can be found here: http://www.cc.puv.fi/~e1301192/projekti/tulos.html
So the search bar at the bottom is supposed to filter divs and display only those, that contain certain keyword. (t.ex, if you type Digital Electronics, it will display only Divs that contain text "Digital Electronics II" and "Digital Electronics". Right now, if I type random gibberish, it hides everything like it's supposed to, but when I type in the beginning of a course name, it will not hide the courses that dont contain the certain text-string.
Here is an example that I used (which works fine): http://jsfiddle.net/Da4mX/
Hard to explain, but I hope you realize if you try the search-function on my page. Also, I'm pretty new to javascript, and I get the part where you set the searchbox's string as var search, the rest I'm not so sure about.
Please help me break down the script, and possibly point where I'm going wrong, and how to overcome the problem.
in your case I think you show and hide the parent of courses so you can try
$("#filterTextBox").on("keyup", function () {
var search = $(this).val().trim().toLowerCase();
$(".course").show().filter(function () {
return $(this).text().toLowerCase().indexOf(search) < 0;
}).hide();
});
Try this this is working now, paste this code in console and check, by searching.
$("#filterTextBox").on("keyup", function () {
var search = this.value; if( search == '') { return }
$( ".course" ).each(function() {
a = this; if (a.innerText.search(search) > 0 ) {this.hidden = false} else {this.hidden = true}
}); })
Check and the search is now working.
Your problem is there :
return $(".course", this)
From jquery doc: http://api.jquery.com/jQuery/#jQuery-selection
Internally, selector context is implemented with the .find() method,
so $( "span", this ) is equivalent to $( this ).find( "span" )
filter function already check each elements
then, when you try to put $(".course") in context, it will fetch all again...
Valid code :
$("#filterTextBox").on('keyup', function()
{
var search = $(this).val().toLowerCase();
$(".course").show().filter(function()
{
return $(this).text().toLowerCase().indexOf(search) < 0;
}).hide();
});
In fact, you can alternatively use :contains() CSS selector,
but, it is not optimized for a large list and not crossbrowser
http://caniuse.com/#search=contains
You were accessing the wrong elements. This should be working:
$(".kurssikurssi").find('.course').show().filter(function () {
var $this = $(this)
if($this.text().indexOf(search) < 0){
$this.hide()
}
})
Related
My first time writing my own javascript/jQuery for-loop and I'm running into trouble.
Basically, I have a series of divs which are empty, but when a button is clicked, the divs turn into input fields for the user. The input fields are there at the outset, but I'm using CSS to hide them and using JS/jQuery to evaluate the css property and make them visible/hide upon a button click.
I can do this fine by putting an id tag on each of the 7 input fields and writing out the jQuery by hand, like this:
$('#tryBTN').click(function(){
if ( $('#password').css('visibility') == 'hidden' )
$('#password').css('visibility','visible');
else
$('#password').css('visibility','hidden');
}
Copy/pasting that code 7 times and just swapping out the div IDs works great, however, being more efficient, I know there's a way to put this in a for-loop.
Writing this code as a test, it worked on the first one just fine:
$('#tryBTN').click(function() {
for(i = 1; i <= 7; i++) {
if($('#input1').css('visibility') == 'hidden')
$('#input1').css('visibility', 'visible');
}
});
But again, this only works for the one id. So I changed all the HTML id tags from unique ones to like id="intput1" - all the way out to seven so that I could iterate over the tags with an eval. I came up with this:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
if ($(eval('input' + i)).css('visibility') == 'hidden')
$('input' + i).css('visibility', 'visible');
}
});
When I put in the eval stuff - it doesn't work. Not sure what I'm doing wrong. A sample of the HTML looks like this:
<form>
<div class="form-group">
<label for="page">Description: Specifies page to return if paging is selected. Defaults to no paging.</label>
<input type="text" class="form-control" id="input7" aria-describedby="page">
</div>
</form>
You were forgetting the #:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
var el = $('#input' + i); // <-- The needed `#`
if (el.css('visibility') == 'hidden') {
el.css('visibility', 'visible');
}
}
});
#Intervalia's answer explains the simple error in your code (the missing #), and the comments explain why you should never use eval() unless you absolutely know it's the right tool for the job - which is very rare.
I would like to add a suggestion that will simplify your code and make it more reliable.
Instead of manually setting sequential IDs on each of your input elements, I suggest giving them all a common class. Then you can let jQuery loop through them and you won't have to worry about updating the 7 if you ever add or remove an item.
This class can be in addition to any other classes you already have on the elements. I'll call it showme:
<input type="text" class="form-control showme" aria-describedby="page">
Now you can use $('.showme') to get a jQuery object containing all the elments that have this class.
If you have to run some logic on each matching element, you would use .each(), like this:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
if( $(element).css('visibility') == 'hidden' ) {
$(element).css( 'visibility', 'visible' );
}
});
});
But you don't need to check whether an element has visibility:hidden before changing it to visibility:visible. You can just go ahead and set the new value. So you can simplify the code to:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
$(element).css( 'visibility', 'visible' );
});
});
And now that the only thing we're doing inside the loop is setting the new visibility, we don't even need .each(), since jQuery will do the loop for us when we call .css(). (Thanks #TemaniAfif for the reminder.)
So the code becomes very simple:
$('#tryBTN').click( function() {
$('.showme').css( 'visibility', 'visible' );
});
I'd like to select an element using javascript/jquery in Tampermonkey.
The class name and the tag of the elements are changing each time the page loads.
So I'd have to use some form of regex, but cant figure out how to do it.
This is how the html looks like:
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
The tag always is the same as the classname.
It's always a 4/5 letter random "code"
I'm guessing it would be something like this:
$('[/^[a-z]{4,5}/}')
Could anyone please help me to get the right regexp?
You can't use regexp in selectors. You can pick some container and select its all elements and then filter them based on their class names. This probably won't be super fast, though.
I made a demo for you:
https://codepen.io/anon/pen/RZXdrL?editors=1010
html:
<div class="container">
<abc class="abc">abc</abc>
<abdef class="abdef">abdef</abdef>
<hdusf class="hdusf">hdusf</hdusf>
<ueff class="ueff">ueff</ueff>
<asdas class="asdas">asdas</asdas>
<asfg class="asfg">asfg</asfg>
<aasdasdbc class="aasdasdbc">aasdasdbc</aasdasdbc>
</div>
js (with jQuery):
const $elements = $('.container *').filter((index, element) => {
return (element.className.length === 5);
});
$elements.css('color', 'red');
The simplest way to do this would be to select those dynamic elements based on a fixed parent, for example:
$('#parent > *').each(function() {
// your logic here...
})
If the rules by which these tags are constructed are reliably as you state in the question, then you could select all elements then filter out those which are not of interest, for example :
var $elements = $('*').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
DEMO
Of course, you may want initially to select only the elements in some container(s). If so then replace '*' with a more specific selector :
var $elements = $('someSelector *').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
You can do this in vanilla JS
DEMO
Check the demo dev tools console
<body>
<things class="things">things</things>
<div class="stuff">this is not the DOM element you're looking for</div>
</body>
JS
// Grab the body children
var bodyChildren = document.getElementsByTagName("body")[0].children;
// Convert children to an array and filter out everything but the targets
var targets = [].filter.call(bodyChildren, function(el) {
var tagName = el.tagName.toLowerCase();
var classlistVal = el.classList.value.toLowerCase();
if (tagName === classlistVal) { return el; }
});
targets.forEach(function(el) {
// Do stuff
console.log(el)
})
http://jsfiddle.net/bGDME/
Basically, I want to show only whatever is selected in the scope and hide the rest.
The way I did it seems so.. I don't know. Tedious.
I was hoping to get some ideas of making it better. A point in the right direction would be very much appreciated, too.
Thanks.
You can minimize the code by using toggle() instead of your if/else statements
Working Example: http://jsfiddle.net/hunter/bGDME/1/
$('#scope').change( function(){
var type = $('option:selected', this).val();
$('#grade').toggle(type == 2 || type == 3);
$('#class').toggle(type == 3);
});
.toggle(showOrHide)
showOrHide: A Boolean indicating whether to show or hide the elements.
This seems fine to me, unless you have lots of or dynamic controls. However u can use JQuery addClass / removeClass, switch statement, multiple Selector $('#grade, #class').show(); to minimize the code
you can also use a switch state: http://jsfiddle.net/bGDME/3/
Here's an approach using HTML5 data attributes to declaratively set "scope levels" on the select boxes: http://jsfiddle.net/bGDME/6/
And the updated JavaScript:
var $scopedSelects = $('#grade, #class').hide();
$('#scope').change( function(){
var scopeLevel = $(this).val();
$scopedSelects.each(function() {
var $this = $(this);
$this[$this.data('scope-level') <= scopeLevel ? 'show' : 'hide']();
});
});
The primary advantage this one might have is that the code stays the same regardless of how many "scoped selects" you have (assuming you update the initial selector, of course).
what about this??
$(document).ready( function() {
$('#grade, #class').hide();
$('#scope').change( function(){
var type = $('option:selected', this).text();
alert(type);
$('select').next().not('#'+type).hide();
$('#'+type).show();
});
});
DEMO
Its very simple,
$(document).ready( function() {
$("select[id!='scope'][id!='school']").hide();
$('#scope').change( function(){
$("select[id!='scope']").hide();
var ken=$(this).val();
$("#"+ken).show();
});
});
If you want to make it a bit more dynamic by not touching the javascript when you want to add more select elements, then you can do small changes to your javascript code and HTML and you will only need to edit the HTML
Javascript:
$(document).ready(function() {
$('#scope').change(function() {
var type = $(this).val().split(',');
$('.values select').hide();
for (x in type) {
$('.values').find('#'+type[x]).show();
}
});
});
HTML:
<select id='scope'>
<option value=''>Select</option>
<option value='school'>school</option>
<option value='school,grade'>grade</option>
<option value='school,grade,class'>class</option></select>
This will do what you're looking for: http://jsfiddle.net/bGDME/30/
You simply use the val() of the scope within the eq() method to determine which sibling select should remain shown. If 'school' is chosen from the first dropdown, then neither get shown:
$(document).ready( function() {
var additionalSelects = $('#grade, #class');
$('#scope').change(function(){
var selectedVal = $(this).val();
additionalSelects.hide();
if(selectedVal > 1){
additionalSelects.eq(selectedVal - 2).show();
}
});
});
I have child divs that I'm trying to sort based on a jquery .data() value that I give them that is just a single number. This code works perfectly, but only once, after that I can't figure out how the heck it's sorting them. Here is a simplified version:
var myArray = $('#container div').get();
myArray.sort(function(x,y) {
return $(x).data('order') - $(y).data('order');
});
$('#container').empty().append(myArray);
I've tried so many other different methods of sorting, other plugins, etc., and I can't get anything to work right. This is as close as I can get. I just have this running on a jquery change event.
Here is the whole thing in case I'm doing something stupid elsewhere:
$('#attorneyFilter').change(function() {
//get array of links for sorting
var myArray = $('#attorneyBlocks div').get();
var selectedArea = $(this).val();
//sort alphabetically when "all" is selected
if (selectedArea == 'all') {
$('#attorneyBlocks div').show();
myArray.sort(function(a,b) {
return $(a).text() > $(b).text() ? 1 : -1;
});
//filter attorneys based on practice area and then assign its order# to the div with data, getting all values from the div's class
} else {
$('#attorneyBlocks div').hide().each(function() {
var attorneyArea = $(this).attr('class').split(', ');
for (var i=0;i<attorneyArea.length;i++) {
var practiceArea = attorneyArea[i].split('-');
if (selectedArea == practiceArea[0]) {
$(this).show().data('order',practiceArea[1]);
}
}
});
//sort based on order, the lower the number the higher it shows up
myArray.sort(function(x,y) {
return $(x).data('order') - $(y).data('order');
});
}
//append order back in
$('#attorneyBlocks').empty().append(myArray);
});
And a link to the page in question
Here's a jsFiddle with this working using .detach() instead of .empty() to keep the data.
http://jsfiddle.net/shaneblake/Tn9u8/
Thanks for the link to the site, that made it clear.
It seems to me you never clear out the data from the prior time. You hide everything but maybe something like this will solve your problem (here I set everything hidden to the bottom, you can clear it or use a different value -- as long as it is not the same as any sort key):
$('#attorneyBlocks div').hide().data('order',999999).each(function() {
var attorneyArea = $(this).attr('class').split(', ');
for (var i=0;i<attorneyArea.length;i++) {
var practiceArea = attorneyArea[i].split('-');
if (selectedArea == practiceArea[0]) {
$(this).show().data('order',practiceArea[1]);
}
}
});
Also, the code on the server is missing the 2nd line you have above:
var myArray = $('#attorneyBlocks div').get();
The problem is the change event is tied to the original items. After the sort you make all new items. They don't have any event tied to them. You will need to use .live()
Eventually figured it out, the data values from hidden divs were screwing with my sorting, so I changed my sorting code to only pay attention to :visible divs and that did the trick. Doh! Thanks for your help everyone.
Is there a way to me do this?
<img id="example" src="anything.jpg" title="something" class="abc" />
$('.abc').each(function(){
//test if this result is something
if( $(this)...(???)...('[src^=anything]')) == 'anything.jpg'){
}
//another Jquery selector test for this one
if( $(this)...(???)...('#example').size() > 0){
}
});
This is just an example, what I need is pretty more complex.. But I would like to know if there is a way to make other jQuery selector test in the result of a first selector.. since "find" will find the children of $(this).. and .parent() get alot of brothers..
See what I mean?
Do you have any idea?
So sorry.. let me try again..
$('div').each();
get all "div", right?
But now in that function I need to make another "test" check if div class is "red" or "blue"..
See?
I need to test something else of the result based in Jquery selector..
I know I could do:
class = $(this).attr('class'); and then if(class=="blue"){} .. But I would like to do $('this[class=blue]').size()>0){}
The jQuery is() filter operates on a found set to detect if something is true or not.
The jQuery filter() method will further pare down a found set based on criteria.
var allDivs = $('div');
var greenOnes = allDivs.filter('.green');
var redOnes = allDivs.filter('.red' );
I think you need the is method:
$('.abc').each(function() {
$(this).is('[src^=anything]')
});
This is fairly simple though, but I can't really tell what you are trying to do by the description. Maybe this is enough to get you started though.
You can use the filter and is methods to filter/search within a jQuery object.
if( $(this).is('[src^="anything"]') ) {
}
elseif( $("#example").size() > 0) {
}
You could put $("#example") in a variable outside of the loop and then reference it inside the loop as well.
if(this.src.indexOf("anything") === 0) {
// source starts with 'anything'
}
if($("#example").length) {
// since there can be only one #example
// in a *valid* document
}
Based on your edit:
if($(this).hasClass("blue")) {
...
}
?