There are a lot of questions about select2 doubling values, and many of them don't have accepted answers.
On the surface everything looks fine but when I delete a token it's still sending it in params.
Checking the values of the input (which select2 is hiding)
Prior to initializing select2
$('#language_list').val() //=> "english spanish italian"
After init
$('#language_list').val() //=> "english spanish italian,english,spanish,italian"
// It's clearer what's going on like this.
// And I don't know if it's significant but tokenSeparators: [",", " "]
$("#user_language_list").select2("val") //=> ["english spanish italian", "english", "spanish", "italian"]
Lots of issues are coming up like when the form repopulates after an error I'll have
$('#language_list').val() //=> "english-spanish-italian english spanish italian,english,spanish,italian"
Hidden in my input which I have to address on the backend.
What worked was cleaning the value before sending your data to the callback
You'll probably recognize this as basically the code from the docs.
initSelection: function (e, callback) {
var tags = e.val().split(/, |,| /);
for (var i = 0; i < tags.length; i++) {
var tag = tags[i].trim();
tags[i] = {id: tag, text: tag};
}
callback(tags);
}
But you just need to clean the val
initSelection: function (e, callback) {
var tags = e.val().split(/, |,| /);
e.val("")
for (var i = 0; i < tags.length; i++) {
var tag = tags[i].trim();
tags[i] = {id: tag, text: tag};
}
callback(tags);
}
Related
I have a client who specifically does not like the numbers next in the headers of the columns when doing a sort. This is rooted in UI-Grid's multi-sort, which gives each column a numbered priority. Is there a way to disable the multi-sort in order to remove those numbers? I still want to keep sorting activated, but only on one column at a time.
Thanks.
I've had this problem myself. If you look carefully in the ui0grid.js code you'll see that there is (at this time) no option to diable it. The writers of ui-grid state that they would welcome a request for such a function in this thread
However, you want a fix, not a promise ;-)
You can spot how many sortColumns have been chosen in the sortChanged method.
Try something like this:
$scope.gridOptions.onRegisterApi = function(gridApi) {
$scope.gridApi = gridApi;
// Register a handler that is fired everytime someone changd the sort params.
$scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
if (sortColumns.length > 1) {
// We have more than one sort. Kill the first one.
// If this works we'll only ever have 0, 1 or 2 sortColumns,
// and only ever 2 for the lifetime of this method.
var column = null;
for (var j = 0; j < grid.columns.length; j++) {
if (grid.columns[j].name === sortColumns[0].field) {
column = grid.columns[j];
break;
}
}
if (column) {
sortColumns[1].sort.priority = 1; // have to do this otherwise the priority keeps going up.
column.unsort();
}
}
});
};
This is against the 3.0.0 release of ui-grid.
HTH
To prevent sorting on multiple columns, I added these two lines in the Grid.prototype.sortColumn function, ui-grid.js file.
self.resetColumnSorting(column);
column.sort.priority = undefined;
works for me..
I wanted to limit multiple sort columns to a maximum of 2. This is how I did it.
$scope.gridOptions.onRegisterApi = function(gridApi) {
$scope.gridApi = gridApi;
$scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
if (sortColumns.length == 3) {
//limit multi column sort to max 2 columns
for (var j = 0; j < grid.columns.length; j++) {
if (grid.columns[j].name === sortColumns[2].name) {
grid.columns[j].sort = {};
break;
}
}
return;
});
};
Looks like this is supported now in the HTML element:
[suppressMultiSort]="true"
This in the latest version. No need for tough scripts.
i wanna ask how to change title in
name
so i want to make link name copy to title automatic
so if i make this code
title link
to
title link
how to do that in php or javascript
i know some in php
but need to make all words in link at database or make for every link variable $
can some one help me in that?
I'd suggest:
function textToTitle(elem, attr) {
if (!elem || !attr) {
// if function's called without an element/node,
// or without a string (an attribute such as 'title',
// 'data-customAttribute', etc...) then returns false and quits
return false;
}
else {
// if elem is a node use that node, otherwise assume it's a
// a string containing the id of an element, search for that element
// and use that
elem = elem.nodeType == 1 ? elem : document.getElementById(elem);
// gets the text of the element (innerText for IE)
var text = elem.textContent || elem.innerText;
// sets the attribute
elem.setAttribute(attr, text);
}
}
var link = document.getElementsByTagName('a');
for (var i = 0, len = link.length; i < len; i++) {
textToTitle(link[i], 'title');
}
JS Fiddle demo.
And since it seems traditional to offer a concise jQuery option:
$('a').attr('title', function() { return $(this).text(); });
JS Fiddle demo.
If you don't want to use a library:
var allLinks = document.getElementsByTagName('a');
for(var i = 0; i < allLinks.length; i++){
allLinks[i].title = allLinks[i].innerHTML;
}
Since you wanted to do all this to one element on the page, consider using something like this:
var allLinks = document.getElementById('myelement').getElementsByTagName('a'); // gets all the link elements out of #myelement
for ( int i = 0; i < allLinks.length; i++ ){
allLinks[i].title = allLinks[i].innerHTML;
}
Actually, this is roughly the same as before but we are changing the input elements.
Or, assuming you use jQuery, you could do something like this:
$('a').each(function(){ // runs through each link element on the page
$(this).attr('title', $(this).html()); // and changes the title to the text within itself ($(this).html())
});
In JQuery you can change an attribute by knowing the current tag and using the .attr() feature. Something like $('a').attr('title', 'new_title'); http://api.jquery.com/attr/
Is it possible to filter numbers from the variable.
I can show you one example here from the link http://jsfiddle.net/sweetmaanu/82r5v/6/
I need to get only numbers from the alert message
Simply replace the box string out of it.
DEMO
for (var i = 0; i < order.length; i++) {
order[i] = order[i].replace('box', '');
}
So instead of box1, box2, box3, box4 you want to see 1,2,3,4
You can use a regular expression like this:
var order = $("#boxes").sortable("toArray") + "";
alert(order.replace(/[^0-9,]/g, ''));
I also had to append an empty string to order because it wasn't being recognized as a string object even though the jQuery documentation says it should be when you call sortable("toArray").
change var order = $("#boxes").sortable("toArray");
to var order = $("#boxes").sortable("toArray").join(',').replace(/[a-zA-Z]/gi, "");
Demo: http://jsfiddle.net/82r5v/13/
// Remove all non-digits from the string
'box1'.replace(/\D/g, ''); // => '1'
// Same, but try to make the string a number
Number('box1'.replace(/\D/g, '')); // => 1
// Shorthand for making an object a number (+o is the same as Number(o))
+'box1'.replace(/\D/g, ''); // => 1
// parseInt(s) works if the number is at the beginning
parseInt('1box'); // => 1
// but not if it occurs later
parseInt('box1'); // => NaN
Maybe using regular expressions something like this:
`alert(order.join(',').match(/\d/g));`
To return the array as numbers.
(\d matches all digits, g signifies a global match wildcard)
One way to do it by using regular expressions - http://jsfiddle.net/holodoc/82r5v/14/
$(document).ready(function() {
var arrValuesForOrder = ["2", "1", "3", "4"];
var ul = $("#boxes"),
items = $("#boxes li.con");
for (var i = arrValuesForOrder[arrValuesForOrder.length - 1]; i >= 0; i--) {
// arrValuesForOrder[i] element to move
// i = index to move element at
ul.prepend(items.get(arrValuesForOrder[i] - 1));
}
$("#boxes").sortable({
handle : '.drag',
update: function() {
var order = $("#boxes").sortable("toArray");
var sorted = [];
$.each(order, function(index, value){
sorted.push(value.match(/box(\d+)/)[1]);
})
alert(sorted);
}
});
});
I have to parse a document containing groups of variable-value-pairs which is serialized to a string e.g. like this:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
Here are the different elements:
Group IDs:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
Length of string representation of each group:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
One of the groups:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14 ^VAR1^6^VALUE1^^
Variables:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
Length of string representation of the values:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
The values themselves:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
Variables consist only of alphanumeric characters.
No assumption is made about the values, i.e. they may contain any character, including ^.
Is there a name for this kind of grammar? Is there a parsing library that can handle this mess?
So far I am using my own parser, but due to the fact that I need to detect and handle corrupt serializations the code looks rather messy, thus my question for a parser library that could lift the burden.
The simplest way to approach it is to note that there are two nested levels that work the same way. The pattern is extremely simple:
id^length^content^
At the outer level, this produces a set of groups. Within each group, the content follows exactly the same pattern, only here the id is the variable name, and the content is the variable value.
So you only need to write that logic once and you can use it to parse both levels. Just write a function that breaks a string up into a list of id/content pairs. Call it once to get the groups, and then loop through them calling it again for each content to get the variables in that group.
Breaking it down into these steps, first we need a way to get "tokens" from the string. This function returns an object with three methods, to find out if we're at "end of file", and to grab the next delimited or counted substring:
var tokens = function(str) {
var pos = 0;
return {
eof: function() {
return pos == str.length;
},
delimited: function(d) {
var end = str.indexOf(d, pos);
if (end == -1) {
throw new Error('Expected delimiter');
}
var result = str.substr(pos, end - pos);
pos = end + d.length;
return result;
},
counted: function(c) {
var result = str.substr(pos, c);
pos += c;
return result;
}
};
};
Now we can conveniently write the reusable parse function:
var parse = function(str) {
var parts = {};
var t = tokens(str);
while (!t.eof()) {
var id = t.delimited('^');
var len = t.delimited('^');
var content = t.counted(parseInt(len, 10));
var end = t.counted(1);
if (end !== '^') {
throw new Error('Expected ^ after counted string, instead found: ' + end);
}
parts[id] = content;
}
return parts;
};
It builds an object where the keys are the IDs (or variable names). I'm asuming as they have names that the order isn't significant.
Then we can use that at both levels to create the function to do the whole job:
var parseGroups = function(str) {
var groups = parse(str);
Object.keys(groups).forEach(function(id) {
groups[id] = parse(groups[id]);
});
return groups;
}
For your example, it produces this object:
{
'1': {
VAR1: 'VALUE1'
},
'4': {
VAR1: 'VALUE1',
VAR2: 'VAL2'
}
}
I don't think it's a trivial task to create a grammar for this. But on the other hand, a simple straight forward approach is not that hard. You know the corresponding string length for every critical string. So you just chop your string according to those lengths apart..
where do you see problems?
Facebook has this unique and clever approach to localization of their site: translators (in their case users that help to translate the site voluntarily) can simply click on the not-yet-translated strings – which are marked with a green bottom border – in their natural context on the site. See http://www.facebook.com/translations/.
Now, if you ever had to deal with the translation of a website, you'll be well aware of how odd and funny some of these translations can be when using tools like poedit where the translator isn't fully aware of the spot the translated string will lated appear in on the website.
Example: Please translate "Home". In German, for instance, the start page of a website would be "Home" while the house you live in is "Heim". Now, you as the translator basically have to guess which context this term is likely to appear in on the website and translate accordingly. Chances are, you're new website on home furniture now translates as "Home-Einrichtung" which sounds ridiculous to any German.
So, my question boils down to:
Do you know any open source PHP projects that work on something like this? I'm basically looking for a framework that allows you to put your internationalized website in "translation mode" and make strings clickable and translatable e.g. through a Javascript modal.
I'm not so much looking for a full-fledged and ready-made solution, but would love to know about similar projects that I can contribute code to.
Thanks in advance!
If you want to roll your own with jquery & jquery browserLanguage, this might get you going.
Tag all translatable text's contain elements with class="i18n", and include jquery, jquery browserLanguage, and your i18n script.
1. the internationalization javascript
— this needs to accept translations via ajax from your server, like:
var i18n = {};
i18n.bank = new Array();
i18n.t = function ( text, tl=$.browserLanguage ) {
var r = false;
$.ajax({
url: "/i18n_t.php?type=request&from="+ escape(text) +"&tl="+ tl,
success: function(){ i18n.bank[text] = this; r = true; }
});
return r;
};
2. php i18n translation service
— now we need to serve up translations, and accept them
the database will look like a bunch of tables, one for each language.
// SCHEMA for each language:
CREATE TABLE `en`
(
`id` INT PRIMARY KEY AUTO INCREMENT NOT NULL,
`from` VARCHAR(500) NOT NULL,
`to` VARCHAR(500) NOT NULL
)
the php will need some connection and db manipulation.. for now this may do:
//Connect to the database
$connection = mysql_connect('host (usually localhost)', 'mysql_username' , 'mysql_password');
$selection = mysql_select_db('mysql_database', $connection);
function table_exists($tablename, $database = false) {
if(!$database) {
$res = mysql_query("SELECT DATABASE()");
$database = mysql_result($res, 0);
}
$res = mysql_query("SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = '$database' AND table_name = '$tablename'
");
return mysql_result($res, 0) == 1;
}
the code is simply:
<?php
// .. database stuff from above goes here ..
$type=$_GET["type"];
$from=$_GET["from"];
$to=$_GET["to"];
$tl=$_GET["tl"];
if (! table_exists($tl)) {
...
}
if ($type == "request") { // might want to set $tl="en" when ! table_exists($tl)
$find = mysql_query("SELECT to FROM `'$tl'` WHERE from='$from'");
$row = mysql_fetch_array($find);
echo $row['to'];
} elsif ($type == "suggest") {
$find = mysql_query("SELECT COUNT(*) AS count FROM `'$tl'` WHERE from='$from'");
if ( !(mysql_result($res, 0)) == 0 ) {
$ins = mysql_query("INSERT INTO `'$tl'` (from, to) VALUES ('$from','$to')");
}
}
?>
3. page translation mechanics
— finally we can tie them together in your webpages with some further jquery:
i18n.suggest = function (from) { // post user translation to our php
$.ajax({
url: "/i18n_t.php?type=suggest&from='+from+'&to="+ escape( $('#i18n_s').contents() ) +"&tl="+ $.browserLanguage,
success: function(){ $('#i18n_t_div').html('<em>Thanks!</em>').delay(334).fadeOut().remove(); }
});
};
$(document).ready(function() {
i18n.t("submit");
i18n.t("Thanks!");
$('.i18n').click( function(event) { //add an onClick event for all i18n spans
$('#i18n_t_div').remove;
$(this).parent().append(
'<div id="i18n_t_div"><form class="i18n_t_form">
<input type="text" id="i18n_s" name="suggestion" value="+$(this).contents()+" />
<input type="button" value="'+ i18n.bank[ "submit" ] +'" onclick="i18n.suggest( '+$(this).contents()+' )" />
</form></div>'
);
}).each(function(){
var c = $(this).contents(); //now load initial translations for browser language for all the internationalized content on the page
if ( i18n.t(c) ){
$(this).html(i18n.bank[c]);
}
});
});
Mind you I don't have a server to test this on... and I don't actually code php. :D It will take some debugging but the scaffolding should be correct.