Jquery ui Selectable() cant properly unselect outside the method - javascript

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" );

Related

Hide inactive or disabled elements in the list

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>

jQuery autocomplete search and select programmatically

I have a data from my controller and when the page loads I want the autocomplete input to search for that data and select it.
I am able to search the data using:
$( "#autocomplete" ).autocomplete( "search", '<?=$ID?>' );
above code works and showing the correct value of autocomplete. Now I cant select the value so that the autocomplete input triggers change. I wanted the input to trigger change because I will auto populate some input.
The way I select the value pro grammatically is :
select: function( event, ui ) {}
Now i found this:
search: function( event, ui ) {},
Is is possible to combine the two?
How to select searched data from auto complete programmatically ?
Update:
This is how my autcomplete works:
$( ".updatedautocomplete" ).autocomplete({
source:function(request,response){
var $this = $(this);
$.post("url",{
term:request.term
}).done(function(data, status){
response($.map( data, function( item ) {
return {
data
}
return false; // Prevent the widget from inserting the value.
}));
});
},
select: function( event, ui ) {
$( this ).attr( 'data-value' , ui.item.id );
$( this ).attr( 'data-asd' , ui.item.sad );
$( this ).val( ui.item.label );
$( "#modal" ).val( ui.item.qwe.trim() );
$( "#modal" ).val( ui.item.asd.trim() );
$( "#modal" ).val( ui.item.zxc.trim() );
$( "#modal" ).val( ui.item.ert.trim() );
$( "#modal" ).val( ui.item.dfg.trim() );
return false;
}
});
The reason why I wanted select event is to populate some input as shown in the source
You simply do jQuery.val() on the input element, like so.
Edit
Since you seem to want to trigger the selection after an asynchronous data retrieval, you probably want the response event and perform the selection there.
response (event, ui)
Triggered after a search completes, before the menu is shown. Useful for local manipulation of suggestion data, where a custom source option callback is not required. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled
$(".updatedautocomplete").autocomplete({
source: function(request, response) {
var $this = $(this);
//$.post("url", {
// term: request.term
//})
//.done(function (data, status) {
// response($.map(data, function (item) {
// return {
// data
// }
// return false; // Prevent the widget from inserting the value.
// }));
//
//});
// Simulates some data returned from server
response([
{ label: "Javascript", value: "js" },
{ label: "CSharp", value: "cs" },
{ label: "PHP", value: "php" }
]);
},
response: function(event, ui) {
// Make your preferred selection here
var item = ui.content[0].label;
$(this).val(item).trigger('change');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input class="updatedautocomplete" />
search and select are the events which get triggered when the search is taking place. You don't execute them.
Additionally, I believe the method search (not the event one) is meant rather for "suggesting" users that a value/tag exists in the list and that they need to select it themselves. So, yes, if you need a value programmatically selected (without user interaction) you might need to do it by .val() and optionally .trigger().

How to show autocomplete results in a specific div

I have an autocomplete field into my website. I just want to display the results inside a <div> tag instead the popup window that the plugin opens natively.
I searched already for solutions for this in other posts, but what they do is to change the position of the "popup" window, and what I want is to replace the content of the <div> with the results, not to put the popup over it.
This is my code :
$('#keyword').autocomplete(
{
source : '/Dev/pages/suivi_searchCompany.php',
select: function( event, ui )
{
console.log(ui.item.value);
loadHisto(ui.item.value);
loadInfosCompanies(ui.item.value);
loadInfosContact(ui.item.value)
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item )
{
console.log('test');
console.log(item);
console.log(ul);
return $( "<li>" )
.append( "<a>" + item.name + "</a>" )
.appendTo( ul );
};
An ugly but maybe sufficient solution might be to simply copy the content of the jquery-ui-generated div to your div and hide the default div:
jQuery:
$('#ui-id-1').bind('DOMSubtreeModified', function() {
$('#mycontainer').html($('#ui-id-1').html());
});
Empty custom div if input is empty:
$('#keyword').keyup(function() {
if($(this).val() == '') {
$('#mycontainer').html('');
}
});
CSS:
#ui-id-1 {
display: none !IMPORTANT;
}
JSFiddle
The ID of the default autocomplete div (#ui-id-1) might vary.
UPDATE:
To add one of the possible options from the dropdown to your textbox, add this:
$('#mycontainer').on('click', 'li', function() {
//add option to textbox
$('#keyword').val($(this).html());
//hide / clear dropdown
$('#mycontainer').html('');
});
See updated fiddle (which I tidied up a bit aswell).

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

append a div to another div only once on droppable drop

I have a draggable element , that when its dropped onto the target, it adds a delete button:
$( "#committed" ).droppable({
hoverClass: 'drophover',
drop: function( event, ui )
{
$(function()
{
var done;
if( done ) return;
done = true;
$(ui.draggable).append('<button class="delBtn" type="reset">X</button>');
$(ui.draggable).draggable( "option", "disabled", true );
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
});
}
Once its been dropped, it then becomes sortable. The issue is , everytime the element is sorted, the Delete button gets added again. As there are multiple elements being dragged and dropped and then sorted, so .length>? doesn't work.
I essentially need
If (this.delBtn exists)
I updated another jsfiddle project, there the button is added only if the button does not exist on the draggable object yet: jsfiddle example
The trick here is this:
if ($(ui.draggable).find('button.delBtn').length == 0) {
$(ui.draggable).append('<button class="delBtn" type="reset">X</button>');
}
It checks if the dragged item contains a button with class delBtn. If not then it adds the button.
Wouldn't something like this sort you out?
if($('button.delBtn').length > 0)
{
// The delete button exists...
}

Categories