How can I dynamically resize a select2 input to be the same width as the selected option? - jquery-select2

I'm building a 'natural language' search form using a series of inline select inputs, using jQuery Select2 for styling. The widths of the Select2 inputs appear to be set to the width of the selected option on initialisation, which is great. I just can't work out how to get the width to update when the selected option is changed. Any ideas?
Many thanks!

Try to add this to yor CSS file:
.select2-container {
width: 100% !important;
}
It solved my resize problems with select2
(Edited: I do not use placeholders)

You can use window resize function.
Example:
// Fix select2 width
$(window).on('resize', function() {
$('.form-group').each(function() {
var formGroup = $(this),
formgroupWidth = formGroup.outerWidth();
formGroup.find('.select2-container').css('width', formgroupWidth);
});
});

I know this is an old post However, I had an issue when I used NMC's code.
As I can't comment on his answer, after using his code I had some annoying scrollbars appearing after using the select2 dropdowns, to fix this I used width auto instead.
.select2-container {
width: auto !important;
}

Just had to do something like this for a site
$(e).on("select2:closing", function(e) {
if (e.hasOwnProperty('params') &&
e.params.hasOwnProperty('args') &&
e.params.args.hasOwnProperty('originalEvent') &&
e.params.args.originalEvent.hasOwnProperty('target')) {
var newWidth = $(e.params.args.originalEvent.target).width();
var id = $(e.params.args.originalEvent.target).attr('id');
var container = $("span[aria-labelledby=\""+id.split("-result")[0]+"-container"+"\"]");
$(container).parents('span.select2').width(newWidth + 21);
}
});
This is probably not fool-proof and is tied to the current API. But it gets the width of the element in the dropdown before the dropdown closes and then applies that to the container.
One thing of note, you may need to float the dropdown items to get their real size.
.select2-results__option {
float: left;
clear: both;
}

$('.select2-search__field').attr('style','width:auto');
$('.select2-search__field[placeholder=""]').attr('style','width:10px');

For dynamically resize a select2 you can use width: 'style' option as below:
$('#field_'+field.name).select2({
placeholder: "select a option...",
maximumSelectionLength: 1000 ,
allowClear: true,
...
width: 'style',
data: data
});
And next you have to use style="width:100%;" as attribute for your select tag.
<select class="input-element-item fontsize13" id="select2" style="width:100%;" >
<option></option>
</select>

For other than problems of responsive width, read the documentation of Select2. Everything is explained.
https://select2.org/appearance#container-width
<select class="js-example-responsive" style="width: 50%"></select>
$(".js-example-responsive").select2({
width: 'resolve' // need to override the changed default
});

Related

Highcharts does not resize charts inside tabs

I am using twitter bootstrap with tabs. I have multiple tabs and charts inside each tab. Upon browser resize, charts that are not on the current active tab do not get resized. Infact, it looks kind of funny with a thin bar. The current active tab works fine. Has anyone seen this issue and are there any workarounds ?
Here is a working example:
http://codepen.io/colinsteinmann/pen/BlGfE
Basically the .reflow() function is called on each chart when a tab is clicked. That way the chart gets redrawn based on the new dimensions which are applied to the container when it becomes visible.
This is the most important snippet of code:
// fix dimensions of chart that was in a hidden element
jQuery(document).on( 'shown.bs.tab', 'a[data-toggle="tab"]', function (e) { // on tab selection event
jQuery( ".contains-chart" ).each(function() { // target each element with the .contains-chart class
var chart = jQuery(this).highcharts(); // target the chart itself
chart.reflow() // reflow that chart
});
})
This is my fix for this (using jQuery):
$("[data-highcharts-chart]").each(function () {
var highChart = Highcharts.charts[$(this).data('highchartsChart')];
var highChartCont = $(highChart.container).parent();
highChart.setSize(highChartCont.width(), highChartCont.height());
highChart.hasUserSize = undefined;
});
Call this function whenever the chart gains focus to make sure it is resized properly.
I had a similar issue and I found that the best thing was not to load the chart until the tab was shown. So in the tab shown event I was quickly loading the chart (but only once)
I just solved this issue with the following. Using bootstrap version 3.3.5
I am leaving this here because this link showed up when I googled the issue at the beginning. I hope it helps.
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
$(e.target.hash).highcharts().reflow();
});
HTML
<!-- Nav tabs -->
<ul class="nav nav-pills nav-justified" role="tablist" id="taks-tabs">
<li role="presentation" class="active">Met Standard</li>
<li role="presentation">Commended Performance</li>
<li role="presentation">TAKS-M Met Standard</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="taks_met_std"></div>
<div role="tabpanel" class="tab-pane" id="taks_comm_perf"></div>
<div role="tabpanel" class="tab-pane" id="taks_m_met_std"></div>
</div>
add class="chart" to all highcharts containers inside tabs.
add this jQuery code:
jQuery(document).on( 'shown.bs.tab', 'a[data-toggle="tab"]', function () {
$( '.chart' ).each(function() {
$(this).highcharts().reflow();
});
})
I found the answer after looking for sometime. This was driving me crazy so I want to share it with you all since nothing here worked for me.
Add this to your CSS
.tab-content > .tab-pane,
.pill-content > .pill-pane {
display: block;
height: 0;
overflow-y: hidden;
}
.tab-content > .active,
.pill-content > .active {
height: auto;
}
For more details visit the page I found the solution at
https://jonpolygon.com/bootstrap-tabs-100-percent-width-charts/
i fix this problem with the next code.
$('#yourDivChart').highcharts({
chart: {
type: data.EjeX.Tipo,
//width: width,
//height: height,
options3d: {
enabled: true,
alpha: 15,
beta: 15,
viewDistance: 25,
depth: 40
},
width: $('#DivContainerWithYourTabs').width() - 150
},
in my case is a partial "_partialDetalleProyecto"
I hope works you.
So this is a bit old, but for anyone stumbling across this, I was having a similar issue with the highchart sizes being incorrect in a bootstrap tabbed display. The solution I came up with was to just delay creating the chart by 100ms using setTimeout().
setTimeout(function() {
drawBarChart();
}, 100);
Note: drawBarChart is a custom function I created to generate the charts I needed. The issue (at least in my case) seemed to be that the chart was being created before (or at the same time) as the container and was therefore choosing some default width instead of the width of the container.
I have 2 tabs , met same problem.
I changed only 2 rows codes of Druska, and it worked.
function anyname() {
$("[data-highcharts-chart]").each(function () {
var highChart = Highcharts.charts[$(this).data('highchartsChart')];
var highChartCont = $(highChart.container).parent();
highChart.reflow();
});
}
and add one onclick event to you HTML tab codes like below:
<input type="radio" id="tab1_1" checked onclick="anyname();" >

jQuery UI droppable: resizing element on hover not working

I have a jQuery UI droppable element which I would like to get bigger when a draggable is hovered over it. I have tried both using the hoverClass option and also binding to the drophover event.
Visually, both these methods work fine. However, once the draggable exits the original (smaller) boundary of the droppable, jQuery UI interprets this as a 'dropout', despite still being within the current (larger) boundary.
For example, js:
$("#dropable").droppable({
hoverClass: 'hovering'
}.bind('dropout', function () {console.log('dropout')});
css:
#droppable { background: teal; height: 10px; }
#droppable.hovering { height: 200px; }
In this case, when a draggable hovers over the droppable, the droppable visually increases in size to 200px. If at this point, the draggable is moved down by 20px, I would expect it to still be hovering over the droppable. Instead, jQuery UI fires the dropout event and the droppable reverts to being 10px high.
Anyone know how to get it to behave in the way I'd expect it to?
jsFiddle example: http://jsfiddle.net/kWFb9/
Had the same problem, I was able to solve it by using the following options:
$("#droppable").droppable({
hoverClass: 'hovering',
tolerance: 'pointer'
});
$('#draggable').draggable({
refreshPositions: true
});
Here's the working fiddle: http://jsfiddle.net/kWFb9/51/
See http://bugs.jqueryui.com/ticket/2970
So I made a couple tweaks to your fiddle
First I set the droppable tolerance to "touch" which will activate whenever any part of the draggable is touching it. This causes the hovering class to be applied.
Next I added an animation to resize your draggable element slightly. I wasn't sure if this was functionality you wanted or not so I put it in there anyways.
Lastly, I permanently apply the hovering class to the droppable element when the draggable element is dropped into the droppable zone. This way the droppable doesn't revert to that narrow height when there is an element in it
http://jsfiddle.net/kWFb9/2/
EDIT:
Better fiddle: http://jsfiddle.net/kWFb9/6/
I hope this helps :)
you could create a bigger (i.e. the size of #droppable.hovering) div without background and apply your droppable to it. Note that you didn't provide HTML but the new #drop_container should contain both divs.
JS
var dropped;
$("#droppable").droppable({
drop: function(event, ui) {
dropped = true;
}
});
$('#draggable').draggable({
start: function(event, ui) {
$("#droppable").addClass("hovering");
dropped = false;
},
stop: function(event, ui) {
if (!dropped) {
$("#droppable").removeClass("hovering");
}
}
});
CSS
#droppable { background: teal; height: 10px; }
#droppable.hovering, #drop_container { height: 200px; }
Or you could try another solution with .live() or .livequery() from this article
[EDIT] I've edited my code and here is a jsfiddle: http://jsfiddle.net/94Qyc/1/
I had to use a global var, I didn't find a better way to check wether the box was dropped. If anybody has an idea, that would be great.
There is an other (hum hum) not bad solution :
TL;DR: Fiddle
The problem is that the plugin stores dom element's size values when the widget is created (something like) :
//jquery.ui.dropable.js
$.widget("ui.droppable", {
...
_create: function() {
var proportions,
this.proportions = function() { return proportions; }
And the offset for widgets are initialized in $.ui.ddmanager.prepareOffsets();
So we only need to overwrite the proportions object.
This way allow to access to real plugin properties so we can write something like :
$("#droppable").droppable({
hoverClass: 'hovering',
over: function(ev, ui) {
var $widget = $(this).data('droppable');
$widget.proportions = {
width: $(this).width(),
height: $(this).height()
};
},
out: function(ev, ui) {
var $widget = $(this).data('droppable'); //ui-droppable for latests versions
$widget.proportions = {
width: $(this).width(),
height: $(this).height()
};
}
})

With jQuery, how can I gray out and disable a webpage and then show some kind of spinner on top of that?

I am still pretty "green" when it comes to web development and javascript/jQuery programming, so any help is appreciated. Here is what I want to do.
I want to do the same thing that a jQuery UI dialog box does where it puts a semi-transparent image over the entire page and disables clicking of any of the controls underneath.
I want to know how I might put some kind of spinner overlay on top to show that the website is working in the background. If I can use a animated GIF file that would be fine, but I'm not quite sure on the best approach to this.
Here is an example of the grayed-out effect with a dialog box:
jQuery UI Example. I want to know how to produce this effect without the dialog box on top. I do not have a good example of the spinner behavior.
All suggestions, website referrals, and code is appreciated.
EDIT: I do not mean a "spinner control". I will try to find an example of what I am thinking of by spinner.
EDIT: What I mean by "spinner" is a loading gif of some kind like the "Indicator Big" gif on this website: http://ajaxload.info/
I always like to use the jQuery BlockUI plugin:
http://malsup.com/jquery/block/
Check out the demos, you'll probably find something you're looking for there.
One way to do it is to have a div that is hidden by default and has properties to set the background colour to a grey (#666 for instance) and its transparency set to something like 0.8.
When you want to display use jQuery to get the size of the screen/browser window, set the size of your div and display it with a high zindex, so it displays on top. You can also give this div your spinner gif graphic (no repeat, and centered).
Code:
#json-overlay {
background-color: #333;
opacity: 0.8;
position: absolute;
left: 0px;
top: 0px;
z-index: 100;
height: 100%;
width: 100%;
overflow: hidden;
background-image: url('ajax-loader.gif');
background-position: center;
background-repeat: no-repeat;
}
Only things to watch out for are select elements in IE6, as these will show through the div, so you can either use jQuery bgframe to solve that, or what I have done in the past is just hide select elements when displaying the div and showing them again when hiding your div
Why don't you just use "modal:true"?
$(function () {
$("#dialog").dialog($.extend({}, dialogOptions, {
autoOpen: false,
width: 500,
modal: true,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "fade",
duration: 1000
}
}));
$("#profile_edit").click(function () {
$("#dialog").dialog("open");
});
$("#save_and_close").click(function () {
$("#dialog").dialog("close");
});
});
You can use something like this jquery code. Pass the id of the element that you want to stay on top of the page:
function startModal(id) {
$("body").prepend("<div id='PopupMask' style='position:fixed;width:100%;height:100%;z-index:10;background-color:gray;'></div>");
$("#PopupMask").css('opacity', 0.5);
$("#"+id).data('saveZindex', $("#"+id).css( "z-index"));
$("#"+id).data('savePosition', $("#"+id).css( "position"));
$("#"+id).css( "z-index" , 11 );
$("#"+id).css( "position" , "fixed" );
}
function stopModal(id) {
if ($("#PopupMask") == null) return;
$("#PopupMask").remove();
$("#"+id).css( "z-index" , $("#"+id).data('saveZindex') );
$("#"+id).css( "position" , $("#"+id).data('savePosition') );
}
you can use simple div and then ajaxstart and ajaxstop event
<div id="cover"></div>
$('#cover')
.hide()
.ajaxStart(function () {
$(this).fadeIn(100);
})
.ajaxStop(function () {
$(this).fadeOut(100);
});

Appended new divs, but they're not draggable?

I'm a newbie and have some problems with making new divs draggable.
The example is: http://jsbin.com/iyexi3/
The problem is when I show the dialog for the name, I create some divs, but they aren't draggable.
You've made some elements that are hardcoded in the HTML draggable by doing this:
$('.seleccionable').draggable({
drag: function(e, ui) {
$('#status_nombre').html($(this).attr('id'));
$('#status_top').attr('value',$(this).css('top'));
$('#status_left').attr('value',$(this).css('left'));
}
,containment: '#layout'
,refreshPositions: true
,snap: true
});
When you add a new element you need to call .draggable() for that one too.
One way to do it would be to put that selector/draggable code into a function and call it after you've added a new element.
The issue is that when you append a new element to the DOM, it doesn't inherit the event handlers of the existing draggable elements.
You may have some luck with liveQuery
This will allow you to create live events on all current and future elements matching a selector. It's similar to the built-in live() method. I haven't used it but it should work with draggable.
finally find the solution is afther append the new div...
$('#nv_objeto').click(function(){
var nbr =prompt("Por favor escriba el nombre del Objeto:","");
$("#layout").append("<div id='"+c_nbr(nbr)+"' class='seleccionable' style='top: 300px; left: 400px; width : 40px; height : 40px; background-color : black; position :absolute;'></div>");
$('#layout > div:last').blur().draggable({
drag: function(e, ui) {
$('#status_nombre').html($(this).attr('id'));
$('#status_top').attr('value',$(this).css('top'));
$('#status_left').attr('value',$(this).css('left'));
}
,containment: '#layout'
,refreshPositions: true
,snap: true
});
});
thanks for the help.

getting jQuery UI's datepicker to always open in a certain direction?

I'm using jQuery UI's datepicker control in a position: fixed toolbar at the bottom of my page. Occasionally, on random computers, the datepicker appears below the toolbar, which means it's off the page and impossible to view or interact with.
Is there a way to force the positioning of the datepicker control to always be above and to the right of its <input>?
The only way to be certain (for the jQueryUI version of datepicker) is to disable the functionality of the datepicker that tries to render inside the viewport. Here's a way to do it without modifying the source code files:
$.extend(window.DP_jQuery.datepicker,{_checkOffset:function(inst,offset,isFixed){return offset}});
on later versions of JQuery UI try:
$.extend($.datepicker,{_checkOffset:function(inst,offset,isFixed){return offset}});
That just nukes the _checkOffset function inside datepicker that makes it squirrelly. Then you can use the .ui-datepicker css to make sure it stays fixed if that's what you're after. More info at how-to-control-positioning-of-jqueryui-datepicker.
Problem is that element in position: fixed show top position 0px (check with: alert$('#datepicker2').position()).
Solution:
$('#datepicker').datepicker( {beforeShow: function(input) {
var x = 100; //add offset
var y = 20;
field = $(input);
left = field.position().left + x;
bottom = y;
setTimeout(function(){
$('#ui-datepicker-div').css({'top':'', 'bottom':bottom + 'px', 'left': left + 'px'});
},1);
}}
Test HTML:
<form style="position:fixed; bottom:0; width:100%" name="form1" method="post" action="">
<label>
<input style="left:300px; position:absolute; bottom:0" type="text" name="textfield" id="datepicker">
</label>
</form>
You could change the lines:
offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0;
offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0;
...to read:
offset.left = $(inst.input).position().left + dpWidth;
offset.top = $(inst.input).position().top - dpHeight;
This loses flexibility, though. If your input happens to be at the top of the page, you'll have the opposite problem from before.
http://www.mindfiresolutions.com/Make-jQuery-datepicker-to-popup-in-different-positions-995.php
check this. I used this and was able to position the datepicker control in all browsers.
I had a similar problem. I have a page with date pickers potentially used at various placed on the page but also on a fixed header where the user can scroll the page both horizonally and vertically with the fixed header staying in place. The header also has a datepicker. So I can't do a global change of datepicker.
This is what I did. It is admittedly a kluge but it works so I thought it might help someone else. Hopefully in the future the jquery datepicker will add a position option.
beforeShow: function(input, inst) {
$("#ui-datepicker-div").css({ "visibility": "hidden", "display": "none" );
window.setTimeout(function() {
var leftPosition = parseInt($(window).width() / 2);
$("#ui-datepicker-div").css({ "position": "fixed", "top": 0, "left": leftPosition });
$("#ui-datepicker-div").css({ "visibility": "visible", "display": "inherit" );
}, 500);
}
From the documentation, it looks like you might be able to use the 'dialog' method of the datepicker plugin to achieve your desired outcome. However, using this most likely means that you will have to implement some of the glue that you would otherwise get out-of-the-box with datepicker, such as a callback handler to extract the date, etc.
I tried to mock up some code to see it in action and short of getting the datepicker to display, I couldn't quite get it working, though. Anyway, I wanted to point you to it in case you have better luck than I did.

Resources