select2 'change' event doesn't trigger for the first time - javascript

I have Select2 Javascript widget on my page.
$('#order_address_select').select2({
placeholder: "Select adress",
ajax: {
url: '<?=Yii::app()->getBaseUrl(true)?>/order/getplacemarklist',
dataType: 'json',
},
tags: true,
});
When I'm typing some text, and if it is not found in database and not loaded through ajax, I can anyway choose it, cause attribute tags is setted to true. Then I have following code
$('#order_address_select').change(function () {
alert($("#order_address_select option[data-select2-tag='true']").val());
});
The problem is when I'm typing text, and selecting it as a tag, event doesnt trigger for the first time. But when I'm typing text again, and selecting it, code alerts value of previously selected option. For example: I'm typing "aaa", selecting it, nothing happens, then I'm typing "bbb", selecting it, and got alert with "aaa"

So, if anyone is interested, I found solution on select2 github repository, you just need to add an empty <option></option> to your <select>. And then it will work fine

Inside my change handler I get the selected option as
var data = $(this).select2("data")[0];
Like this:
$selectXXXXX.on('change', function (e) {
var data = $(this).select2("data")[0];
var cfg = configuraciones[data.id];
app.usersFocusChange(data.id, cfg);
});
Ref: select2 dox

You can resolve it by manipulating html :
$('#yourselect2').append("<option selected value='your_val'>your_text</option>");

Related

Click on first item autocomplete jQuery ui

I'm trying to click on the first item of the list that displays autocomplete after searching:
$(function(){
$('#autocompleteplace').each(function(i, el) {
var $this = $(el);
$this.autocomplete({
source: $this.data('urlp'),
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
$('#' + $this.data('id')).val(ui.item.id);
}
});
var region = '{{ form.vars.data.place.region|default('') }}';
$this.autocomplete("search", region, true);
var menu = $this.autocomplete("widget");
$(menu[0].children[0]).click();
});
});
This code is the same from here, which I tried in the same environment and it works. But in my example I get the data from the server, and it shows and selects the first item with autoFocus, but it doesn't click on it.
I just want to edit a post that uses a field with autocomplete (place), so when the form is shown I want it to have the place already selected.
I asked for a quick fix of that problem: retrieve the value of the item that its already stored, but it's easier and cleaner doing it in the form. My fix was modify the Transformer in my Symfony form. Since this is not a PHP topic, I'm not going into details.
In conclusion: there should be a better way to achieve that than forcing a click() event.

Javascript variable seems to be static

I'm trying to develop a website written in PHP which includes a page that users use it to register on website.
In selecting country section of this page, I'm trying to use LOOPJ (http://loopj.com/jquery-tokeninput/demo.html) jQuery Autocomplete script.
When I try to search and make a suggestion list, I want to send another field's data which is located in a textbox in the form. So I tried to use the following code:
$(document).ready(function() {
var countryfrom = $("input#country2").val();
$("#city-input-custom-limits").tokenInput("autocomplete/city_search.php?country=" + countryfrom, {
searchDelay: 1000,
minChars: 3,
tokenLimit: 1
});
});
Everything is working fine. But when I change "country2" text box value, the value of the countryfrom does not change and initial value of the country2 returns to city_search.php page.
Could anyone make suggestions why countryfrom value does not change while country2 is changed?
You should listen to keyup event:
// Cache the element
var $elem = $("#city-input-custom-limits");
$("#country2").on('keyup', function() {
var country = $.trim(this.value);
$elem.tokenInput("autocomplete/city_search.php?country=" + country, {
searchDelay: 1000,
minChars: 3,
tokenLimit: 1
});
}).triggerHandler('keyup'); // execute the handler on DOM ready

Modify CKEditor link dialog to add custom attribute to links

I am using CKEditor on a website and I need to be able to put a special data attributes on some of the links created through the editor. The user would indicate that they need the special attribute put on the link by checking a checkbox in the link dialog. I have managed to add a checkbox to the link dialog with the following code:
CKEDITOR.on('dialogDefinition', function(ev) {
if (ev.data.name == "link") {
var info = dialog.getContents("info");
info.elements.push({
type: "vbox",
id: "urlOptions",
children: [{
type: "hbox",
children: [{
id: "button",
type: "checkbox",
label: "Button",
commit: function(data) {
data.button = this.getValue()
console.log("commit", data.button, data);
},
setup: function(data) {
this.setValue(data.button);
console.log("setup", data.button, data);
}
}]
}]
});
}
});
Now I have two problems. The first one is that despite me adding the code in the commit and setup functions that should save the state of the checkbox, it's not working. It's as if the data can't hold any other parameters but the ones there by default.
The second problem is that I don't know how to add / remove the data attribute on my links. It seems to me that I should be doing that in my onOk callback on the dialog, however, the link dialog already has an onOk callback, so I'm not sure how I should be proceeding. I, of course, do not want to modify any of CKEditor's files directly.
How can I accomplish these things?
You best option is to modify the plugin. So you need to open the source code and find the file links.js in c:\ckeditor_3.6.5\ckeditor\_source\plugins\link\dialogs\
The source code is quite big (40k) but here you can modify the dialog however you want. When you finish just copy it to your plugins folder, and compress it: http://jscompress.com/
I have done what you need myself. The whole uncompressed file is here: https://gist.github.com/3940239
What you need to do:
First add this line just before the dialog "browse" button is appended. Approx. in line: 547:
{
id: "button",
type: "checkbox",
label: "Button",
setup: function (data) {
this.allowOnChange = false;
if (data.button)
this.setValue(data.button);
this.allowOnChange = true;
},
commit: function (data) {
data.button = this.getValue()
this.allowOnChange = false;
}
},
This part is actually your code. I just copied and pasted it.
Then, go to the onOk function, approx. in line 1211: and after commitContent add this code:
this.commitContent( data );
//My custom attribute
if (data.button)
attributes["custom-attribute"] = "button";
else
attributes["custom-attribute"] = "";
This will modify your link adding the attribute to the element such as text
That's it. Although, you may also like to load the current status of the checkbox. Then, go to the function parseLink . Approx. line 179 to load the attributes:
...
if ( element )
{
retval.button = element.getAttribute('custom-attribute');
var target = element.getAttribute( 'target' );
...
I am exploring the same thing now. What I have decided to do at this point is to:
Get a base ckeditor install without the link plugin
create my own fork of the link plugin, and add my changes to it, then activate and use this plugin within the group that link normally shows up in.
...working with it as a custom plugin (albeit a copy of the original) should alleviate the problem of upgrading. You just simply do not use the original link plugin at all. Copy and rename it, and use your custom copy instead.

JQuery - Has Internet Explorer problems with dynamic tables?

My script creates dynamic input fields inside a table. When I try to run a function after an action it doesn't work (In Internet Explorer, everywhere else it's working fine)
I found out that everything works properly, when the input fields come from static HTML.
Do you know something if IE has some problems with dynamically inserted input fields?
The code is simple and works everywhere else:
.append($('<input>')
.attr('type', 'text')
.attr("name","avz_anzahl["+avz_array+"][]")
.attr("size","3")
.attr("bez","avz_anzahl")
.attr("nr","")
.attr("onblur","test();")
.attr("value", "")
Somehow the follwing function doesn't get executed in Internet Explorer:
function test()
{ alert("ok"); }
Do you know why?
In order to make sure jQuery events are working, use proper jQuery events, like bind or blur.
Also jQuery have more elegant way to create html element:
$("input", {
type: "text",
name: "avz_anzahl["+avz_array+"][]"
size: 3,
bez: "avz_anzahl",
nr: "",
blur: test,//make sure there is no (),
click: function(){
},
value: ""
}).appendTo(SomeElement);

How do you ignore hidden page elements when validating using jquery.validationEngine.js?

I have a div who's style defaults to "display: none" until a previous field has been filled out, and it contains a drop down list that requires a selection.
If the page is submitted before this div becomes visible, the validation error appears to the left half-off the page.
This is not a functional problem of course, but I've been wondering if there's a way to have the validation engine ignore hidden elements.
So far I've tried class="validate[optional: Special]" as pointed out on the creator's blog: "optional: Special: Only validate when the field is not empty *Please call optional first". It doesn't seem to work as suggested.
<div id="container" style="display: none;">
...
<select id="mapLocation" onchange="moveMapToCenter();" class="validate[optional: Special]" />
...
</div>
I've also tried using jquery.validate "ignore":
$(document).ready(function() {
$("#aspnetForm").validationEngine({
ignore: ":hidden"
success: false,
failure: function() {}
})
});
This may be a simple oversight on my part, we'll see! Thanks.
I ended up solving this by adding and removing the validation[required] class attribute through functions that hide and show the element.
function showContainer() {
...
$("#mapLocation").addClass("validate[required]");
...
}
function hideContainer() {
...
$("#mapLocation").removeClass("validate[required]");
}
This works fairly well to avoid validation error messages showing up in strange places when hiding page elements that require validation.
i need disable temporary more fields, i make this, a pretty solution:
a little jquery extension:
jQuery.extend(jQuery.fn, {
switchValidationEngine: function (enable) {
$.each(this, function (i, n) {
var field = $(n);
var rulesParsing = field.attr("class");
var newVal = enable ? rulesParsing.replace(/validate_not\[/g, "validate[") : rulesParsing.replace(/validate\[/g, "validate_not[");
field.attr("class", newVal);
});
}
});
usage to disable a field validation:
$("#txtModel").switchValidationEngine(false);
usage to re-enable a field validation:
$("#txtModel").switchValidationEngine(true);

Categories

Resources