Javascript Help on Dropdown filter - javascript

I was able to find a solution on Stackoverflow that display HTML "li" elements based on a filter (see attachement). Essentially based on css class'es defined in HTML elements, it populates the drop down list that you can select from.
I would like to be modify javascript below so that when you navigate to one of the "li" elements pages (as seen here: https://jsfiddle.net/quwfmepL/2/ e.g. Note: Chose one Test1 element and it goes to the page1.html page) ..but when you hit the back button on the page1.html to page where filter resides, it doesn't remember last filter choice. As it does now, you are required to filter same choice again. I think what I need to do is look at the browser history, but not sure if there is an easier option. I was hoping it could be in the format of query string or like.
<script type="text/JavaScript">
$(document).ready(function() {
var $tagList = $('#tag-list'),
optionArr = [];
$("#demo-list li a").each(function(index, item) {
$.each($(this).attr('class').split(' '), function(i, option){
if ($.inArray(option, optionArr) == -1) {
$tagList.append('<option value="'+option+'">'+option.replace('-', ' ').replace('_', ' ')+'</option>');
optionArr.push(option);
}
});
});
// Look at the URL for filter and modify here #
$tagList.on('change', function() {
var selection = $tagList.val();
if (selection == "all") {
$('#demo-list li a').show();
} else {
$('#demo-list li a').hide();
$('#demo-list li a.'+selection).show();
}
});
});
</script>
Any suggestions or hints? Any help is appreciated.

Fiddle is acting a bit strangely (not working) for me.
You may want to just set a cookie inside of the .change function, that'd probably be the easiest way to do it. When the filter page loads, check to see if the cookie is set, and if it is, run the filter based on the stored cookie value.
Try out: https://github.com/js-cookie/js-cookie
Alternatively, and probably even better, you can use webstorage (localstorage) to accomplish the same thing.
http://www.w3schools.com/html/html5_webstorage.asp

Related

Format text as user inputs in a contenteditable div

I'm attempting to make a page that allows users to input text and it will automatically format the input -- as in a screenplay format (similar to Amazon's StoryWriter).
So far I can check for text with ":contains('example text')" and add/remove classes to it. The problem is that all of the following p tags inherit that class.
My solution so far is to use .next() to remove the class I added, but that is limited since there might be need for a line break in the script (in dialogue for instance) and that will remove the dialogue class.
$('.content').on('input', function() {
$("p.input:contains('INT.')").addClass("high").next(".input").removeClass("high");
$("p.input:contains('EXT.')").addClass("high").next(".input").removeClass("high");
});
I can't get || to work in the :contains parameter either, but that's the least of my issues.
I have a JS fiddle
I've worked on this for a while now, and if I could change only the node that contains the text (INT. or EXT. in this example) and leaves the rest alone that would work and I could apply it to the rest of the script.
Any help would be appreciated, I'm new to the stackoverflow so thank you.
See the comments in the code below for an explanation of what's going on.
Fiddle Example
JQuery
var main = function(){
var content = $('.content');
content.on('input', function() {
$("p.input").each(function() {
//Get the html content for the current p input.
var text = $(this).html();
//indexOf will return a positive value if "INT." or "EXT." exists in the html
if (text.indexOf('INT.') !== -1 || text.indexOf('EXT.') !== -1) {
$(this).addClass('high');
}
//You could include additional "if else" blocks to check and apply different conditions
else { //The required text does not exist, so remove the class for the current input
$(this).removeClass('high');
}
});
});
};//main close
$(document).ready(main);

How to get ids from divs that were dragged into a drop zone on button click javascript

I'm trying to find a way to get the ids from dragged divs after they are in the drop zone.
All the drag components have an id from drag1 - drag8 and the drop zone is div drop zone. Because there are no divs in the drop zone when the page loads I want to gather the ids on a save button for now with a text box entry and drop down menu select.
I have tried the code below:
$(document).ready(function() {
$("#dropzone div").click(function() {
var index = $("#dropzone div").index(this);
$("#dropzone_drag").html("Index " + drag + " was clicked");
});
});
And I use jQuery for the text box, which works nicely:
$(document).ready(function() {
$('#save').click(function() {
alert($('#name').val());
});
});
How do I find the ids from dragged divs after they are in the drop zone?
After playing around i came up with the following:
var ids = {};
$("#dropzone>div").each(function(i){
ids[i] = $(this).prop('id');
});
which at the moment says undefined, but i did manage to put it on the save button so it no longer pops up when i open the page.
Any suggests please?
In my comprehension .index(this) returns the index of the element relative to the list "#dropzone div"., which may or may not contain the elements in the order you want. But if all your elements have a common class, say ".foo_bar" it probably would be easier to know the id given an clicked element.
Otherwise, as you're using this on the function, if this is one of your "drags" it is probably easier to pick the id from this than to try the indexes.
Try doing it like that and maybe it'll word better.
ids = {};
$("#dropzone>div").each(function(){
ids[$(this).prop('id')] = $(this).prop('id').replace(/[^0-9]/g, '');
});
the code .replace() means that we are removing characters (in this case anything that isn't a number) from the string so we end up with it's true number. Instead of it's place in the DOM.
If i didn't comprehend well your problem, correct my comprehension errors and i will edit the answer. And an html of the zones would be nice ;)
The following code worked for me:
<script>
var div = document.getElementById('dropzone')
</script>
and on the button i added:
alert( div.innerHTML )
The result gave me all of the div information from it's html page so i could select the information i wanted to push to the database.
Thank you all for you input and advice.
Matthew

How do i recognize a ctrl+click on an html webpage with javascript/jquery?

I am making an application which makes use of context menus and has selection. Right now i can select 1 element, but what i want to do is to ctrl+click to allow me to say append the elements into an array for the selection of MULTIPLE elements simultaneously. That way i can affect the attributes of N things at the same time.
I Need it to be something like Control+Clicking, if there was a better idea, i could be interested. Maybe Shift+click but that has the general understanding of selecting everything ebtween X and Y, where as users are more familiar with clicking individual items with ctrl.
I know how to do the append thing, but i wasnt sure how to do the:
var ev = mouse||window.event;
var t_sel = ev.target || ev.srcElement;
...
$('.item').click(function(e) {
if (e.ctrlKey || e.metaKey) {
// required code to make selection
// propably, add class to item to style it like selected item and check hidden checkbox
$(this).toogleClass('selected');
$(this).find('input[type=checkbox]').attr('checked', !$(this).find('input[type=checkbox]')('checked'));
}
});
This will allow you to detect a control click:
$(document).click(function(e) {
if(e.ctrlKey) {
//You do your stuff here.
}
});
I've used shiftcheckbox to have the ability to select a range of checkboxes in a grid.
The code is available so you can alter it to fit your needs. You may also use it as inspiration for a functionallity that suits you.
https://github.com/nylen/shiftcheckbox

jQuery UI Tabs: Targeting Dynamic Tab from a Link

Recently I've been looking at opening a tab using this script:
$('.tofour').click(function() { // bind click event to link
$tabs.tabs('select', 3); // switch to third tab
return false;
});
However my specific problem is that the site I'm working on does not always load the same tab set. The tabs can change dependent on whether certain information exists. Example:
In certain situations we'll have enough data for:
Product Data (#overview)
Specifications (#specs)
Accessories (#accessories)
Services (#services)
Customer Reviews (#reviews)
And in other situations there will be only enough data to populate two tabs
Product Data (#overview)
Accessories (#accessories)
As you can imagine this creates a problem as the tab number can change; the Specification tab (#specs) might be either the second tab, or the first tab (if Product Data doesn't exist), or Specifications tab might not exist at all.
So, for the sake of argument, lets say I wish to target the Specifications tab. I guess the first thing would be to check if the div id #specs exists. Then I guess I've got to create a link that will target that. But can I target an id instead of a tab number, as in the usual example (above)?
Can anyone help with this? My jQuery skills are, I'm ashamed to admit, pretty poor.
I thank you kindly in advance.
You could get the index via this code, then check if it's -1 (that means it doesn't exist)
Note: This assumes that the a tag for the tab has the id of specs
var index = $('#tabs a').index($('#specs'));
if (index > -1) {
$('#tabs').tabs('select', index);
}
Create a javascript array containing the tab id as the key and the tab index as the value:
// if you're using php and the tabs that need to be generated are in a variable called $tabs
// you could work this out in other languages
$count = count($tabs);
for($i=0;$i<=$count;$i++){
$tab = $tabs[$i];
echo 'tab_indexes[' . $tab['id'] . '] = ' . $i . ';'; // id as in #specs, etc
}
Then use the array in jQuery:
$('#to_specs').click(function() { // bind click event to link
$('#tabs').tabs('select', tab_indexes['#specs']); // switch to specs tab
return false;
});
This should be good for the scenario
You can replace element.id.match('specs') with your desired condition
$('.tofour').click(function(evt) {
$('#tabs a').each(function(index,element){
if(index != -1 && element.id.match('specs')){
$('#tabs').tabs('select', index);
return false;
}
});
});
$("#m").live('click',function(){
$('#tabs').tabs({ selected: "#tabs-1" });
});
Try this. Let me know further.

jquery checkbox slow, not sure how to fix

I have used firebug and IE profilers and can see what function in my code is causing the slowness. Being new to jquery, the recommendations that I have read online are not clear to me. I have made an example page that shows the slow behavior when you check or uncheck a check box. No surprise that this is fast using Chrome.
The function that is slow can be found on line 139.
$('.filters input').click( function()
JSFiddle can be found here
The code is 122 KB and can be found here
UPDATE: if you know of any examples online that are similar in function and faster, please share.
i had a brief look through your code, but it was very hard to follow. it seemed as if you were looping through things many many times. i used a much simpler approach to get the list of all states.
your approach was
* make a massive string which contained every class (possibly repeated multiple times)
* chop it up into an array
* loop through the array and remove duplicates
i simply took advantage of the fact that when you select something in jQuery you get a set rather than a single item. you can therefore apply changes to groups of object
$(document).ready(function () {
//this will hold all our states
var allStates = [];
//cache filterable items for future use
var $itemsToFilter = $(".filterThis");
//loop through all items. children() is fast because it searches ONLY immediate children
$itemsToFilter.children("li").each(function() {
//use plain ol' JS, no need for jQuery to get attribute
var cssClass = this.getAttribute("class");
//if we haven't already added the class
//then add to the array
if(!allStates[cssClass]) {
allStates[cssClass] = true;
}
});
//create the container for our filter
$('<ul class="filters"><\/ul>').insertBefore('.filterThis');
//cache the filter container for use in the loop
//otherwise we have to select it every time!
var $filters = $(".filters");
// then build the filter checkboxes based on all the class names
for(var key in allStates) {
//make sure it's a key we added
if(allStates.hasOwnProperty(key)) {
//add our filter
$filters.append('<li><input class="dynamicFilterInput" type="checkbox" checked="checked" value="'+key+'" id="filterID'+key+'" /><label for="filterID'+key+'">'+key+'<\/label><\/li>');
}
}
// now lets give those filters something to do
$filters.find('input').click( function() {
//cache the current checkbox
var $this = $(this);
//select our items to filter
var $targets = $itemsToFilter.children("li." + $this.val());
//if the filter is checked, show them all items, otherwise hide
$this.is(":checked") ? $targets.show() : $targets.hide();
});
});
FIDDLE: http://jsfiddle.net/bSr2X/6/
hope that's helpful :)
i noticed it ran quite a bit slower if you tried to slideup all the targets, this is because so many items are being animated at once. you may as well just hide them, since people will only see the ones at the top of the list slide in and out of view, so it's a waste of processor time :)
EDIT: i didn't add logic for show all, but that should be quite a trivial addition for you to make if you follow how i've done it above
You could use context with your selector:
$('.filters input', '#filters_container').click(function()...
this limits the element that jQuery has to look in when selecting elements. Instead of looking at every element in the page, it only looks inside your $('#filters_container') element.

Categories

Resources