Hide inactive or disabled elements in the list - javascript

I am struggling with the following issue.
On my wordpress website I have a dropdown filter lists
1. VEHICLE TYPE (convertible, coupe etc.)
2. MAKE (Mercedes, BMW etc.)
3. MODEL (CLK, X5 etc.)
so, when selecting the VEHICLE TYPE from the FIRST list,
appears the corresponding MAKES in the SECOND one for the selected item,
and in the THIRD list appears then the model coresponding the MAKE (Mercedes-CLK, BMW-X5).
Now the thing is, that the Makes or Models that are disabled or inactive won't show on DESKTOP but on MOBILE they appear although still inactive.
1ST question: How can I hide the disabled elements from the list on MOBILE?
2ND question: Can I disable the MAKES and MODELS unless chosen VEHICLE TYPE?
Here below you can see the backend code for the list.
var car_dealer = {};
(function ($) {
/*
* Cleans the form URL from empty parameters on submit
*/
$('.vehicle-search-form').submit( function() {
$(this).find( "input[type='number']" ).filter(function(){
return ($(this).attr( 'min' ) == $(this).attr( 'value' ) || $(this).attr( 'max' ) == $(this).attr( 'value' ));
}).attr( 'disabled', 'disabled' );
$(this).find( "input[type='search']" ).filter(function(){
return ! $(this).val();
}).attr( 'disabled', 'disabled' );
$(this).find( "select" ).filter(function(){
return ! ( $(this).val() && $(this).val() != '-1');
}).attr( 'disabled', 'disabled' );
})
/*
* Disables all models that do not fit the selected make
*/
$('#car_dealer_field_vehicle_type').on('change',function(){
var makeName = $(this).find( 'option:selected' ).attr( 'data-type' );
$('#car_dealer_field_make option')
// first, disable all options
.attr( 'disabled', 'disabled' )
// activate the corresponding models
.filter( '[data-type="' + $.trim( makeName ) + '"], [value="-1"]' ).removeAttr( 'disabled' )
// remove previous value
.parent().val( -1 );
});
$('#car_dealer_field_make').on('change',function(){
var makeName = $(this).find( 'option:selected' ).attr( 'data-make' );
$('#car_dealer_field_model option')
// first, disable all options
.attr( 'disabled', 'disabled' )
// activate the corresponding models
.filter( '[data-make="' + $.trim( makeName ) + '"], [value="-1"]' ).removeAttr( 'disabled' )
// remove previous value
.parent().val( -1 );
});
}(jQuery));
I am grateful and looking forward to hear from you soon !

I know this is old but here we go.
Here is the event handler - reworked a slight bit to only have one selection event handler.
Now as far as the hiding and showing, simply do that to the appropriate list of options filtered as you indicate to hide the disabled ones.
Use prop("disabled",true) to disable, not an attribute.
I left out how to re-enable and show when that is needed but that is a simple
.find('option').prop('disabled",false).show();
(function($) {
/* * Cleans the form URL from empty parameters on submit */
$('.vehicle-search-form').on('submit', function(e) {
// might want to prevent the submit?
e.preventDefault();
$(this).find("input[type='number']")
.filter(function() {
return ($(this).attr('min') == $(this).attr('value') ||
$(this).attr('max') == $(this).attr('value'));
}).prop('disabled', true);
$(this).find("input[type='search']")
.filter(function() {
return !$(this).val();
}).prop('disabled', true);
$(this).find("select").filter(function() {
return !($(this).val() && $(this).val() != '-1');
}).prop('disabled', true);
});
// here we can create one custom event handler to do the disable
$('#car_dealer_field_make')
.on('change', function() {
var makeName = $(this).find('option:selected').data('make');
$(this).trigger("custom-set-me", [makeName, "fun"]);
});
$('#car_dealer_field_vehicle_type')
.on('change', function() {
let makeName = $(this).find('option:selected').data('type');
$(this).trigger("custom-set-me", [makeName, "fun"]);
})
// add the other one to the handler
.add("#car_dealer_field_make")
/*
* Disables all that do not fit the selected
*/
.on('custom-set-me', function(event, compareTo, param2) {) {
let iamMe = $(this);
let options = iamMe.find('option');
options
.prop('disabled', true)
// activate the corresponding models
.filter(function() {
return $(this).data('type') == $.trim(compareTo);
}).val(-1).prop('disabled', false);
// remove previous value
iamMe.val(-1);
options.filter(':diabled').hide();
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

javascript additional text change, on button click in jQuery isotope, other than filter function

I have following - jquery Isotope based filter implemented in my code, its filtering n displaying - filtered content, based on BUTTON click:
function getHashFilter() {
// get filter=filterName
var matches = location.hash.match( /filter=([^&]+)/i );
var hashFilter = matches && matches[1];
return hashFilter && decodeURIComponent( hashFilter );
}
$( function() {
var $container = $('.isotope');
// bind filter button click
var $filterButtonGroup = $('.filter-button-group');
$filterButtonGroup.on( 'click', 'button', function() {
var filterAttr = $( this ).attr('data-filter');
// set filter in hash
location.hash = 'filter=' + encodeURIComponent( filterAttr );
});
// bind filter on select change
$('.filters-select').on( 'change', function() {
// get filter value from option value
var filterValue = this.value;
// use filterFn if matches value
filterValue = filterFns[ filterValue ] || filterValue;
$container.isotope({ filter: filterValue });
});
var isIsotopeInit = false;
function onHashchange() {
var hashFilter = getHashFilter();
if ( !hashFilter && isIsotopeInit ) {
return;
}
isIsotopeInit = true;
// filter isotope
$container.isotope({
itemSelector: '.offer-type',
layoutMode: 'fitRows',
// use filterFns
filter: filterFns[ hashFilter ] || hashFilter
});
// set selected class on button
if ( hashFilter ) {
$filterButtonGroup.find('.is-checked').removeClass('is-checked');
$filterButtonGroup.find('[data-filter="' + hashFilter + '"]').addClass('is-checked');
}
}
$(window).on( 'hashchange', onHashchange );
// trigger event handler to init Isotope
onHashchange();
});
//# sourceURL=pen.js
</script>
Button code:
<div id="filters" class="button-group filter-button-group">
<div class="my123">
<ul>
<li>
<button class="button" data-filter=".a1">Red Apples</button>
</li>
<li>
<button class="button" data-filter=".b1">Green Apples</button>
</li>
</ul>
</div>
</div>
I am trying to change display value of following code, based on same button click. Means additional function, other than filteration.
<blockquote>
<p>
Value to be changed on each button click
</p>
</blockquote>
Tried so many things , but nothing worked. Help please.
var $filterButtonGroup = $('.filter-button-group');
$filterButtonGroup.on( 'click', 'button', function() {
var filterAttr = $( this ).attr('data-filter');
// set filter in hash
location.hash = 'filter=' + encodeURIComponent( filterAttr );
$("blockquote p").html("The value of data attr on button is" + filterAttr);
});
PS : You should definately use an id or class name for your blockquote's paragraph and also if you are using data attribute you can directly access it without attribute i.e
$(this).attr('data-filter');
works same as
$(this).data('filter')

Jquery ui Selectable() cant properly unselect outside the method

I have a table with selectable objects as follow :
/* ESPACE OU LES TATOUAGES SONT SELECTABLE */
$(".tatooInk > tbody").bind("mousedown", function(e) {
e.metaKey = true;
}).selectable();
$( ".tatooInk > tbody" ).selectable({
filter: ":not(td, img ,b,span,div)",
/* Quand on select un tatoo */
selected: function( e, ui ) {
if(tatoos.length < 28){
// JSON.stringify(ui.selected);
console.log($( ui.selected ).html());
$( ui.selected ).addClass( "ui-state-highlight" );
getAllTats( $(ui.selected) );
updateCode();
}
else{
alert('trop de tatouages');
$(ui.selecting).removeClass("ui-selecting");
}
},
unselected: function( e, ui ) {
$( ui.unselected ).removeClass( "ui-state-highlight" );
removeTat( $(ui.unselected) );
updateCode();
}
});
This code works great, when i select an item in my list it looks like this :
At another place in my code, i do some modification depending what has been selected
At another, another, place in my code, if the conditions are meeted i unselect manually using this code
function TabletatooDel(url){
$('.tatooInk tr').each(function(){
var lien = $(this).children(':nth-child(1)').children().attr('src');
if(lien == url){
$(this).removeClass('ui-selected ui-state-highlight');
$(this).trigger('unselecting');
$(this).trigger('unselected');
}
});
}
When passing through that, this is what i think happens :
Even if i removed every Class, when i click on the previously unselected element, even if it goes like this again
The modifications depending on my select DOESNT run.
I have to unselect it again, by clicking on it, and reselect it again in order to have the modifications running.
Any idea how to properly unselect out of the method ?
... It's ok ! I found my problem. I forgot to erase the tatoo out of a json list containing them all.
It looks like this now :
for(var i=0; i< tatoos.length; i++){
if(tatoos[i].url === url ){
tatoos.splice(i, 1);
}
}
$(this).removeClass('ui-state-highlight');
$(this).removeClass('ui-selected');
$(this).children(':nth-child(4)').removeClass( "tatooSelect" );

Selector for filtered items with jQuery tableSorter plugin [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This got into my head lately and honestly I think its worth asking. Here is the thingy..
I have a table , just like any other ordinary table with jquery tablesorter plugin with the filter widget. On the very right of the table columns I've put a checkbox and above that column, on the table headers on that columhn I have another checkbox which has a function linked to it, so that when it gets clicked all the checkboxes get updated with this checkbox's value .
This is not very fancy or sophisticated and I have two way of accomplishing this .. either using a jquery selector or plain old javascript.
so here is what I want todo .. I want to filter elements of the table, then click the checkbox on the header , and I want to affect the row's checkboxes that were filtered with the plugin.
anyone has something to say about this?
thanks .
I already have a demo set up for that here
$( function() {
// using .on() which requires jQuery 1.7+
$( 'table' ).on( 'tablesorter-initialized', function() {
// class name to add on tr when checkbox is checked
var highlightClass = 'checked',
// resort the table after the checkbox is modified?
resort = true,
// if a server side database needs to be updated, do it here
serverCallback = function( table, inputElement ) {},
$table = $( this ),
c = this.config,
wo = c && c.widgetOptions,
// include sticky header checkbox; if installed
$sticky = c && wo.$sticky || '',
doChecky = function( c, col ) {
$table
.children( 'tbody' )
.children( 'tr:visible' )
.children( 'td:nth-child( ' + ( parseInt( col, 10 ) + 1 ) + ' )' )
.find( 'input[type=checkbox]' )
.each( function() {
this.checked = c;
$( this ).trigger( 'change' );
});
};
$table
.children( 'tbody' )
.on( 'change', 'input[type=checkbox]', function() {
// ignore change if updating all rows
if ( $table[0].ignoreChange ) { return; }
var col, $this = $( this );
$this.closest( 'tr' ).toggleClass( highlightClass, this.checked );
$this.trigger( 'updateCell', [ $this.closest( 'td' ), resort ] );
// if your server side database needs more parameters, add them here sent to the callback
serverCallback( $table[0], this );
// uncheck header if any checkboxes are unchecked
if ( !this.checked ) {
$table.add( $sticky ).find( 'thead input[type=checkbox]' ).prop( 'checked', false );
}
})
.end()
.add( $sticky )
.find( 'thead input[type=checkbox]' )
// Click on checkbox in table header to toggle all inputs
.on( 'change', function() {
// prevent updateCell for every cell
$table[0].ignoreChange = true;
var c = this.checked,
col = $( this ).closest( 'th' ).attr( 'data-column' );
doChecky( c, col );
// update main & sticky header
$table.add( $sticky ).find( 'th[data-column=' + col + '] input[type=checkbox]' ).prop( 'checked', c );
$table.children( 'tbody' ).children( 'tr:visible' ).toggleClass( highlightClass, c );
// update all at once
$table[0].ignoreChange = false;
$table.trigger( 'update', [ resort ] );
})
.on( 'mouseup', function() {
return false;
});
});
$('table').tablesorter({
theme: 'blue',
widgets: ['zebra', 'stickyHeaders','filter'],
headers: {
0: { sorter: 'checkbox' }
}
});
});
Just make sure to include the parser-input-select.js file

unwrap list items in jquery based on controller value

I have two side menus. Each menu has subitems as list items under unordered list, like
- FIRST MENU
- Link one
- Link two
- SECOND MENU
- Link three
- Link four
When page loads I want to open one menu and other menu list items should stayed unwrapped
like
- FIRST MENU
- Link one
- Link two
- SECOND MENU
I have working example with FIRST MENU unwrapped here but I do need example with unwrapped SECOND MENU so I can change it to dynamic value sent from my controller.
var unwrapped_menu = $data_sent_from_controller;
if data_sent_from_controller == "SECOND MENU"
then unwrapped second menu.
Changed this example here to hardcoded SECOND MENU unwrapped would be perfect. Nothing more.
If you need more info please ask.
If the dynamic value sent from the controller is the index (starting from 0) of the menu to be opened then:
JSFIDDLE
dynamic_value_from_controller = 1;
$(document).ready(function() {
$.easing.def = "easeOutBounce";
var menus = $( 'div.menu ul li.submenu' ),
current_submenu = null;
menus.next().hide();
menus.each( function(i){
var dropdown = $( this ).next(),
title = $( 'a.title', this );
title.click( function(e){
if ( current_submenu !== null && current_submenu != dropdown )
{
current_submenu.slideUp( 'slow' );
}
current_submenu = dropdown;
dropdown.stop(false, true).slideToggle('slow');
e.preventDefault();
} );
if ( i == dynamic_value_from_controller )
title.click();
});
});
If the dynamic value is the text of the title then:
JSFIDDLE
dynamic_value_from_controller = 'SECOND MENU';
$(document).ready(function() {
$.easing.def = "easeOutBounce";
var menus = $( 'div.menu ul li.submenu' ),
current_submenu = null;
menus.next().hide();
menus.each( function(i){
var dropdown = $( this ).next(),
title = $( 'a.title', this );
title.click( function(e){
if ( current_submenu !== null && current_submenu != dropdown )
{
current_submenu.slideUp( 'slow' );
}
current_submenu = dropdown;
dropdown.stop(false, true).slideToggle('slow');
e.preventDefault();
} );
if ( title.text() == dynamic_value_from_controller )
title.click();
});
});
Have your controller output something on the submenu that you want to open, e.g. a data attribute, or a class name. Then your JS can trigger the submenu that has said attribute or class name to open.
Your list item that you want to open should look something like this:
<li id="second_menu" class="submenu" data-open-on-load="true">
... then in your js, instead of if( i==0 ) you can do something like this:
if ( $(this).attr("data-open-on-load") )
title.click();
See example: http://jsfiddle.net/cWXm5/13/
Note that you'll need to have your controller output this on the first submenu when no others will be set to open, or none will open.

Javascript Autocomplete email's domain using jQuery UI

I need help, I am stuck with trying to make the following case scenario work:
You have email input field, you type: foo#y - it should pop up autocomplete box, offering yahoo.com (for example).
If you take this suggestion, the end value should become: foo#yahoo.com
I have wrote this code (modified off another jquery UI sample):
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 3,
source: function( request, response ) {
var mail_regex = /^([\w.]+)#([\w.]+)$/;
var match = mail_regex.exec(request.term);
if (match)
var matcher = new RegExp( "^" + match[2], "i" );
response( $.grep( availableTags, function( item ){
return matcher.test( item );
}) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
Full working interactive sample:
http://jsfiddle.net/rRF2s/3/
However, it REPLACES the foo# with just yahoo.com - I can not for the life of me figure out how to override this behaviour...
Any Javascript/jQuery masters - help please! how to accomplish this goal?
I tried doing: return match[1]+matcher.test( item ), but that does not work.
The select function is assigning the resultant value with this.value =. However it is replacing the input value completely rather than appending it with the drop down value.
Without a great deal of testing the following, simplified function seems to work as required:
select: function( event, ui ) {
this.value = this.value.substring(0, this.value.indexOf('#') + 1) + ui.item.value;
return false;
}
This is taking the first part of the already entered value, for example foo# for the input foo#ya and then adding on the value of the selected item from the drop down.
You may want to trigger the dropdown when someone enters the # symbol (seems more intuitive to me) and if so, this function may also need modifying to correctly extract the user entered value.
Here is the complete code:
$(function() {
var availableTags = [
"Yahoo.com",
"Gmail.com"
];
function extractLast( val ) {
if (val.indexOf("#")!=-1){
var tmp=val.split("#");
console.log(tmp[tmp.length-1]);
return tmp[tmp.length-1];
}
console.log("returning empty");
return "";
}
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 1,
source: function( request, response ) {
var mail = extractLast(request.term);
if(mail.length<1){return;}
var matcher = new RegExp( "^" + mail, "i" );
response( $.grep( availableTags, function( item ){
return matcher.test( item );
}));
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = this.value.split(", ");
// remove the current input
var ml=terms[terms.length-1].split("#")[0];
terms.pop();
// add the selected item
terms.push( ml+"#"+ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});

Categories