How can I set maximumSelectionLength while closeOnSelect is false in Select2? - javascript

I have the following code:
$("#select2").select2({ closeOnSelect: false,
maximumSelectionLength: 5,
... // I have AJAX implemented here
});
When I have closeOnSelect to be false and have the maximumSelectionLength set, I'm able to select more than 5 items without any problem. When I click away from the dropdown while having more than 5 items selected and I try to add another, I get the message "You can only select 5 items".
Is there any workarounds to have these two properties work together without clashing?
I'm currently using Select2 4.0.1.
Update:
I took pratikwebdev's advise and added the following code:
$("#select2").select2({ closeOnSelect: false,
maximumSelectionLength: 5,
... // I have AJAX implemented here
}).on("change", function(e) {
if(e.target.length == 5) {
$("#select2").select2({closeOnSelect: true,
maximumSelectionLength: 5,
});
}
});
This actually will close the dropdown once I select 5 items and the maximumSelectionLength property will work properly. But now the closeOnSelect is true so each time I select something, the dropdown will close.
Is there a way to toggle closeOnSelect?

This should work fine.
$("#select2").change(function(){
var ele = $(this);
if(ele.val().length==5)
{
ele.select2('close');
}
});

Related

select2 change event without removing already selected options

I'm using select2 with multiple options and programmatic access to select also with a button. It works fine but when I click on the button all previously selected values are removed and only the value from the clicked button gets selected. Since I'm using multiple select it would make sense to add the clicked value and leave the previously selected without removing them... Is there another event to trigger besides "change" that does not remove values but adds them instead?
<select id="id_entities" class="js-example-programmatic" style="width:100%" multiple="multiple">
</select>
<td><button id="prefix_{{teu.entity_id}}" class="js-programmatic-set-val" value="{{teu.entity_id}}" name="{{teu.entity}}"><i class="fa fa-plus"></i></button></td>
<td>{{teu.entity}}</td>
<td>{{teu.user}}</td>
<script >
$(".js-example-programmatic").select2({
minimumInputLength: 2,
placeholder: "Select entities...",
allowClear: true,
multiple:true,
delay: 250,
tags:false,
ajax: {
url: '/entities/search/autocomplete/',
dataType: 'json',
data: function (parms, page) { return { title: parms.term }; },
},
});
</script>
<script>
var $example = $('#id_entities');
$("button[id^='prefix_']").click(function(){
value = $(this).attr('value');
value_name = $(this).attr('name')
if ($('#id_entities option[value="'+value+'"]').length > 0) {
}
else {
$("#id_entities").append('<option value="'+value+'">'+value_name+'</option>');
}
$example.val(value).trigger("change");
});
</script>
well, without seeing a working demo, I assume what you want is to append tags on to a select2 without erasing what tags/multi-selects are already there? If so, you would need to evaluate the element value, and append new vals rather than just calling $example.val(value), which replaces the value of said element
var data = $(test).select2('data');
data.push({id:5,text:"fixed"});
$(test).select2("data", data, true); // true means that select2 should be refreshed
Seels like a duplicate of SELECT2 -> Add data without replacing content

tablesorter does not work when i add more columns

I have a table where i sort on the second column. by default i have 8 columns
and the rows can vary, depending on how many things i add.
The sorting works when i have the standard 8 columns but when i mark a checkbox and save which indicates that more info will be generated dynamiclly in my table then the sorting does not work anymore.
code:
$.tablesorter.addParser({
id: 'input_text',
is: function (s) {
// return false so this parser is not auto detected
return false;
},
format: function (s) {
return s;
},
type: 'text'
});
// Tablesorter
if ($(".attendanceList tbody tr").length > 0) {
$(".attendanceList").tablesorter({ headers: { 1: { sorter: false },
2: { sorter: 'input_text' },
3: { sorter: false },
4: { sorter: false },
5: { sorter: false },
6: { sorter: false },
7: { sorter: false },
8: { sorter: false },
9: { sorter: false },
10: { sorter: false }
},
sortList: [[2, 0], [0, 0]]
});
}
I used firebug to see what the problem was and my "s" paramater(check above) is allways an empty string ("").
step by step:
i mark a checkbox and press a save button. when that is done i press on another button that triggers a popup and gets me my table, now the table has 10 columns but the second column will no longer perform the sort as it did before.
Have i missed something? I have read up on the tablesorter plugin and I have not found anyone with similar issues,
Thanks!
I see two issues with what you are describing; and hopefully you're using my fork of tablesorter.
1) To get the value of a checkbox, you'll need to search the cell for an input and check for updates. Note this parser will work with the original tablesorter, but it won't update (using the updateCell method) properly. Note this code is from the parser-input-select.js file, and can be seen working in this demo.
// Custom parser for including checkbox status if using the grouping widget
// updated dynamically using the "change" function below
$.tablesorter.addParser({
id: "checkbox",
is: function(){
return false;
},
format: function(s, table, cell) {
// using plain language here because this is what is shown in the group headers widget
// change it as desired
var $c = $(cell).find('input');
return $c.length ? $c.is(':checked') ? 'checked' : 'unchecked' : s;
},
type: "text"
});
// update select and all input types in the tablesorter cache when the change event fires.
// This method only works with jQuery 1.7+
// you can change it to use delegate (v1.4.3+) or live (v1.3+) as desired
// if this code interferes somehow, target the specific table $('#mytable'), instead of $('table')
$(window).load(function(){
// resort the column after the input/select was modified?
var resort = true,
// this flag prevents the updateCell event from being spammed
// it happens when you modify input text and hit enter
alreadyUpdating = false;
$('table').find('tbody').on('change', 'select, input', function(e){
if (!alreadyUpdating) {
var $tar = $(e.target),
$table = $tar.closest('table');
alreadyUpdating = true;
$table.trigger('updateCell', [ $tar.closest('td'), resort ]);
// updateServer(e, $table, $tar);
setTimeout(function(){ alreadyUpdating = false; }, 10);
}
});
});
2) The only thing that isn't clear from the question is if the table is being built dynamically within the popup, or if the table with the checkbox is being modified, then copied to a popup?
Note that the above method only updates the state of the checkbox within the table. It won't include any dynamically added columns to an already initialized table. In that case, you'll need to use the updateAll method, but it will need to be triggered after the table contents have been updated.
$table.trigger('updateAll', [ resort ]);
If you could share the code that is run between the time of "saving" your checkbox choices and initializing the popup, it would help make the issue more clear.
Update: to parse an input, you need to get the value of the input element. The s within the parser format function only contains the text found within the table cell. When there is only an input within the table cell, no text is returned because the input element doesn't contain text, it has a value. So instead of using the "checkbox" parser I shared above, use this "input" parser; but as stated before, this parser will work with the original version of tablesorter (v2.0.5) but will not work properly if the "updateCell" method is used.
$.tablesorter.addParser({
id: "inputs",
is: function(){
return false;
},
format: function(s, table, cell) {
return $(cell).find('input').val() || s;
},
type: "text"
});
This parser also requires the code within the $(window).load(...) shown above to allow updating the parsed input for sorting when the user changes it.
After inserting the dynamically-generated content, you just need to trigger an update. It looks like your table is identified with the "attendanceList" class, so the command after the dynamic update would be:
$(".attendanceList").trigger("update");

dojo datagrid IndirectSelection also selects the disabled cells

By selecting all rows in this fiddle: http://jsfiddle.net/Hh8Ub/ you will notice that the disabled checkboxes (rows 1, 3 and 5) are also selected.
I've seen same behaviour in dojo 1.9
One way to solve this might be to modify the toggleAllSelection and run a function foreach row to check if the checkbox is disabled first, but I would rather not to.
this is the toggleAllSelection function:
toggleAllSelection:function(checked){
// summary:
// Toggle select all|deselect all
// checked: Boolean
// True - select all, False - deselect all
var grid = this.grid, selection = grid.selection;
if(checked){
selection.selectRange(0, grid.rowCount-1);
}else{
selection.deselectAll();
}
this.toggleAllTrigerred = true;
},
thanks in advance

Moving jquery accordion elements from one accordion to another

Bit of an odd one, this. I have two jquery accordion entities, and on click of an item in one accordion, I want to dynamically add it to a second accordion, and hide it in the original.
This currently works great moveing from A to B, and on moving back from B to A, BUT when I move an item back to original accordion, any subsequent moves from A to B screw up.
Here's a jsfiddle example of what I mean http://jsfiddle.net/waveydavey/CAYth/ . Note I am compeltely aware that the code is ugly - I'm just learning this stuff. Please feel free to suggest ways that are 10 times better. Do the following:
Run the fiddle.
Click on the "+" of each item to move to accordion 2
All move really well.
Now do this:
Run the fiddle.
Click on any "+" to move to 2nd accordion
Click on "x" on moved item, it re-appears in first set
Click on any "+" item to add to second set
Display completely messes up for accordion item
Any advice would be massively appreciated.
The jsfiddle code is:
$(function() {
// create accordion entities
$('#avAccordion').accordion({
collapsible: true,
autoHeight: false,
active: false
});
$('#assignedAccordion').accordion({
collapsible: true,
autoHeight: false,
active: false
});
$('.accordionAdd').click(function(){
// destroy the accordion, prior to rebuilding
$('#avAccordion').accordion('destroy');
// get the h3 part and tweak it's contents
var h3bit = $(this).parent().clone();
$(h3bit).removeClass('freeContacts').addClass('assignedContacts');
$(h3bit).children('span').removeClass('ui-icon-circle-plus accordionAdd').addClass('ui-icon-circle-close accordionDel');
// get the div part after the h3
var divbit = $(this).parent().next().clone();
// rebuild original accordion
$( "#avAccordion" ).accordion({
collapsible: true,
autoHeight: false,
active: false
});
// move contents to other accordion
$('#assignedAccordion').append(h3bit)
.append(divbit)
.accordion('destroy')
.accordion({
collapsible: true,
autoHeight: false,
active: false
});
// hide original accordion entry
$(this).parent().hide();
//attach click handler to new item
$('.accordionDel').click(function(){
dropAssignedContact(this);
return false;
})
return false;
});
function dropAssignedContact(obj){
// unhide right hand object with appropriate data-id attr
var id = $(obj).parent().attr('data-id');
// delete myself
$(obj).parent().remove();
// unhide original
$('.freeContacts[data-id='+id+']').show();
$('#assignedAccordion').accordion('destroy').accordion({
collapsible: true,
autoHeight: false,
active: false
});
}
});
See this updated fiddle: http://jsfiddle.net/KTWEd/
function dropAssignedContact(obj){
// unhide right hand object with appropriate data-id attr
var id = $(obj).parent().attr('data-id');
// delete myself
$(obj).parent().next().remove(); // <--- Removes the adjacent div
$(obj).parent().remove();
// unhide original
$('.freeContacts[data-id='+id+']').show();
$('#assignedAccordion').accordion('destroy').accordion({
collapsible: true,
autoHeight: false,
active: false
});
}
});

Adding a custom button in row in jqGrid?

I want to make a simple table that contains a custom button in a row. When the button is pushed, I want to pop up an 'alert' box. I have read some posts on this, for example:
this post
and
this other post, and I don't understand why my code is not working. The buttons are drawn, but pushing them has no effect.
I have three attempts described here.
Version 1. The button click never fires:
$(document).ready(function(){
jQuery("#simpletable").jqGrid({
datatype: "local",
colNames:['A','B','Status'],
colModel:[
{name:'A',index:'A'},
{name:'B',index:'B'},
{name:'status',index:status}
],
data:[
{'A':2,'B':100,'status':"<button onclick=\"jQuery('#simpletable').saveRow('1', function(){alert('you are in')});\" >in</button>"},
{'A':1,'B':200,'status':"<button onclick=\"jQuery('#simpletable').saveRow('2', function(){alert('you are in')});\" >in</button>"},
],
caption: "Demo of Custom Clickable Button in Row",
viewrecords:true,
editurl:'clientArray',
});
});
Html Code:
<table id="simpletable"></table>
EDIT 8/2/12 -- I've learned some things since my original post and here I describe two more attempts.
Version 2: I use onCellSelect. This works, but it would not allow me to put more than one button in a cell. Additionally, I made the code nicer by using the format option suggested by one of the comments to this post.
function status_button_maker_v2(cellvalue, options, rowObject){
return "<button class=\"ver2_statusbutton\">"+cellvalue+"</button>"
};
jQuery("#simpletablev2").jqGrid({
datatype: "local",
colNames:['A','B','Status'],
colModel:[
{name:'A',index:'A'},
{name:'B',index:'B'},
{name:'status',index:status,editable:true,formatter:status_button_maker_v2}
],
data:[
{'A':2,'B':100,'status':"In"},
{'A':1,'B':200,'status':"Out"}
],
onCellSelect:function(rowid,icol,cellcontent,e){
if (icol==2){
alert('My value in column A is: '+$("#simpletablev2").getRowData(rowid)['A']);
}else{
return true;
}
},
caption: "Demo of Custom Clickable Button in Row, ver 2",
viewrecords:true,
}); //end simpletablev2
Markup:
<style>.ver2_statusbutton { color:blue;} </style>
<h3>simple table, ver 2:</h3>
<table id="simpletablev2"></table>
Version 3: I tried to use the solution to w4ik's post, using ".on" instead of deprecated ".live". This causes the button click to fire, but I don't know how to retrieve the rowid. w4ik also struggled with this, and he posted that he worked it out, but not how he did it. I can get the last row selected, but this will always refer to the previous row selected because the button is taking priority.
I would prefer this solution if I could get it to work.
jQuery("#simpletablev3").jqGrid({
datatype: "local",
colNames:['A','B','Status'],
colModel:[
{name:'A',index:'A'},
{name:'B',index:'B'},
{name:'status',index:status,editable:true,formatter:status_button_maker_v3}
],
data:[
{'A':2,'B':100,'status':"In"},
{'A':1,'B':200,'status':"Out"}
],
caption: "Demo of Custom Clickable Button in Row, ver 3",
viewrecords:true,
onSelectRow: function(){},
gridComplete: function(){}
}); //end simpletablev3
$(".ver3_statusbutton").on(
{
click: function(){
//how to get the row id? the following does not work
//var rowid = $("#simpletablev3").attr('rowid');
//
//it also does not work to get the selected row
// this is always one click behind:
//$("#simpletablev3").trigger("reloadGrid");
rowid = $("#simpletablev3").getGridParam('selrow');
alert("button pushed! rowid = "+rowid);
}
});
Markup:
<style>.ver3_statusbutton { color:red;} </style>
<h3>simple table, ver 3:</h3>
<table id="simpletablev3"></table>
In summary, I'm struggling with the issue of getting my button to be pushed at the right time. In version 1, the row gets selected and the button never gets pushed. Version 2 does not use the "button" at all -- It just handles the cell click. Verion 3 gets the button click before the row select (wrong order).
Any help would be appreciated!
You can use action formatter here with each row and make edit and delete button as false in formatOptions like this:
formatoptions: {editbutton:false,delbutton:false}}
And follow these two demos:
http://www.ok-soft-gmbh.com/jqGrid/Admin3.htm
http://ok-soft-gmbh.com/jqGrid/TestSamle/Admin1.htm
And on click event of these custom buttons show your alert:
EDIT
var getColumnIndexByName = function (grid, columnName) {
var cm = grid.jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i++) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
},
function () {
var iCol = getColumnIndexByName(grid, 'act');
$(this).find(">tbody>tr.jqgrow>td:nth-child(" + (iCol + 1) + ")")
.each(function() {
$("<div>", {
title: "Custom",
mouseover: function() {
$(this).addClass('ui-state-hover');
},
mouseout: function() {
$(this).removeClass('ui-state-hover');
},
click: function(e) {
alert("'Custom' button is clicked in the rowis="+
$(e.target).closest("tr.jqgrow").attr("id") +" !");
}
}
).css({"margin-right": "5px", float: "left", cursor: "pointer"})
.addClass("ui-pg-div ui-inline-custom")
.append('<span class="ui-icon ui-icon-document"></span>')
.prependTo($(this).children("div"));
});
}
If you check this code, I'm trying to find out index value by giving column name as 'act', you can get index on any other column by giving a different column name.
var iCol = getColumnIndexByName(grid, 'Demo'); and the rest of the code will be same for you. //demo is the column name where u want to add custom button
and write your click event for this button.
Let me know if this works for you or not.

Categories

Resources