Changing the source of an autocomplete widget - javascript

I have a strange problem with a jquery autocomplete widget.
First I have a 'select' HTML element which displays all the projects.
I also have an input element in which I can search for questionnaires which correspond to the selected project.
So I have this code : http://jsfiddle.net/AMkKX/1/
Everything works great. But my problem is when I refresh the page (with F5, not Ctrl+F5) : the previous choice of the select box is always selected so I want to change the source of the autocomplete widget (the code I show you should do that)
But the source doesn't change unless I put an alert before $('#search-questionnaire').autocomplete('option', 'source', data); :
$('#search-project').change(function () {
var data;
var val = $(this).val();
alert('val : ' + val);
if (val != '')
data = questionnairesData[val];
else
data = allQuestionnairesData;
$('#search-questionnaire').autocomplete('option', 'source', data);
});
So I don't understand. Is it a bug ?
EDIT : I can't show you the 'F5 refresh' thing with jsfiddle. If you want to test it you have to copy the code and use it in your navigator.

I haven't tested your code, but from the looks of it, this is a timing issue. I encountered this in Javascript a couple of times. To solve this, try using a setTimeout of 0ms:
Instead of
$('#search-questionnaire').autocomplete('option', 'source', data);
Try:
setTimeout(function() {
$('#search-questionnaire').autocomplete('option', 'source', data);
}, 0)
Let me know how this goes.

Related

Change thousands sign using JS

Here I would like to replace in the draggable slider the "," sign used for the thousands into this sign " ' " (a quote mark).
I am currently using a plugin to render the table (from a JSON file) so I cannot alter the HTML.
I am able to change the sign, in fact on page load the sign seems correct, but as soon I drag the slider the separator changes to a comma again.
I saw that the data is rendered from the Plugin with a comma in the aria-valuetext="" attribute: <div class="noUi-handle noUi-handle-upper" data-handle="1" tabindex="0" role="slider" aria-orientation="horizontal" aria-valuemin="0.0" aria-valuemax="100.0" aria-valuenow="100.0" aria-valuetext="2,290.00"><div class="noUi-tooltip">2,290.00</div></div>
I tried using this code without any results:
<script>
window.onload = function(){
var div = document.querySelectorAll('.noUi-tooltip');
div.forEach(function(r) {
var text = r.textContent;
var output = text.replace(/[,|]/g, "'");
r.innerHTML = output;
});
}
</script>
What am I writing wrong?
I am using WordPress and the wpdatatables plugin.
I'm not sure about the plugin you've used for your slider but perhaps you can try this for now:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type == "attributes") {
var parentEl = document.getElementsByClassName('noUi-handle-upper');
var childEl = parentEl.childNodes[0];
childEl.innerHTML = childEl.innerHTML.replace(',', '\'');
}
});
});
observer.observe(document.getElementsByClassName('noUi-handle-upper')[0], {
attributes: true,
});
It's using MutationObserver which is not supported by older browsers. You can read more about it at https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver.
This is because you modify the string just in the beginning (on load).
This is why the code works in the beginning but doesn't work later, because it runs once and then stops.
I don't know how to use WordPress or sliders, but I'd advise you to use an 'on value changed' command, so the text will change to whatever you want it to each time the slider's value is changed.
I will post this now but I'll review your code and will try to update this with more exact information later.

SessionStorage Navigation

Greets, so I I'm trying to learn jquery/javascript storage and ran into an issue where I am building a navigation that should remember and place you where you last were if you refresh the page (that's why i use sessionStorage rather then localStorage).
But I can't seem to change the sessionStorage variable to the new location, nor figure out a functional way to get the user back on refreshing the page.
This is what I currently have.
$(function() {
sessionStorage.setItem('position', '.first');
var location = sessionStorage.getItem('position');
$('li', this).click(function() {
cls = $(this).text();
if('.' + cls != location) {
$(location).slideToggle(400);
$('.' + cls).delay(400).slideToggle(400);
sessionStorage.setItem('position', '.' + cls)
console.log(location)
};
});
});
https://jsfiddle.net/Unkn0wn96/ndj9sqpe/
The code works in an very odd way, rather then how it's intended, including never changing the value when I console.log(location).
I made some further testing on this and found a 'more' working way in the was that the sessionStorage does change to something, yet it not being usefull.
https://jsfiddle.net/Unkn0wn96/nkbtykkr/
but yet, they elements don't toggle as they should, including that when I console log sessionStorage.position it returns NaN. Also for some odd reason I can't store sessionStorage.position within a variable, it just refuses to change its value. I have no clue why this is happening.
So I was finally able to solve my issue with sessionStorage, since there was not much of help I'd assume the information regarding the case was limited and so wish to share my solution. All thought it does not work fully as intended it does execute it's main function.
$(function() {
$('button').on('click', function() {
var msg = '.'+$(this).text();
localStorage.setItem('color', 'blue') //Default (does not matter since the if statement does not register)
if(msg != '.' + localStorage.color) { // DOES NOT REGISTER
if(localStorage.length > 0) {
localStorage.removeItem('color')
console.log('localStorage.length : ' + localStorage.length)
};
localStorage.setItem('color', msg)
console.log(localStorage.color)
} else {
console.log('cancelled')
}
});
});
https://jsfiddle.net/mdqjoz69/4/
So what I finally was able to achieve was to make a localStorage key change it's value regarding of what button you press.
What I failed to achieve was being able to check the stored data to not execute whenever you store something that have already been stored. There might be a work around for this. But since the code serves its main purpose I'll let it slide.

chart.getSelection() does not work properly with google bar charts

drawBarChart = function (data) {
//few statements goes here which sets options which are being passed to chartDraw i.e. t.options.chart.options
gChart = new google.visualization.BarChart(chartingPlace);
//setTimeout(function () {
// t.options.chart.options.height = ((t.chart.size.height) - 40) + "px";
////console.log(JSON.stringify(t.options.chart.options));
//google.visualization.events.addListener(gChart, 'ready', function () {
// grab a few details before redirecting
google.visualization.events.addListener(gChart, 'select', function () {
var selectedItem = gChart.getSelection()[0];
console.log(gChart.getSelection());
if (selectedItem) {
var topping = data.getValue(selectedItem.row, 0);
alert('The user selected ' + topping);
}
// });
});
gChart.draw(data, t.options.chart.options);
}
My app having a number of charts displaying for different scenarios. My requirement is, click on a bar from google bar chart and open a new tab associated with the name of the bar. For this purpose, I tried using direct 'select' event on bar chart as follows:
google.visualization.events.addListener(gChart, 'select', function () {
var selectedItem = gChart.getSelection()[0];
console.log(gChart.getSelection());
if (selectedItem) {
var topping = data.getValue(selectedItem.row, 0);
alert('The user selected ' + topping);
}
});
But I could not get, this returned empty array for gChart.getSelection(), so I tried the code with 'ready' event mentioned in as first code above.
It works, but not output is not consistent. sometimes it gives empty array and sometimes with selected object.
I am still not able to find why it is showing this kind of behavior
More info: my application is having different tabs, showing number of bar,line,area,combo charts on it. getSelection() works well with line chart but not able to get the consistent output with bars.
Any help is appreciable.
Please do not mark it as duplicate, as I have gone through other similar questions but they does not answer my issue, I do not have that privilege so I could not comment in replies asking for more clarification.
Similar question here : google visualization-Click event on barchart isStacked: true
Please help!
Thank you in advance!
Updates :
I could not get any answer or any response from here.
This is really very disappointing.
Solution:
This is how i worked out the solution for this problem :
The getSelection could not work for me so i tried click event on bar text. Through the click event i could get the text on bar and i linked it to opn new tab.
If anyone need solution in code, please let me know.
Thank you.
Please go through below code snippet, I corrected or you can say organised the code in different way. If you need further explanation please let me know.
google.visualization.events.addListener(googleChartObj, 'select', function () {
var selectedBar = googleChartObj.getSelection();
////console.log(selectedBar);
data.getRowLabel(selectedBar[0].row);
/// for Bar charts, normally row-parameters are used
/// manipulate on 'data' which refers to data-table to get desired results
});

return display instead of value using jquery jeditable with select and loadurl

I have been using the jeditable library for edit in place and it is working well in most cases. However, I now have a problem trying to show the selected text instead of the selected value when using the loadurl parameter. I've tried all of the solutions from this question however, they don't seem to work with loadurl instead of data. Here is the pertinent code below, and I also have a working (for the most part - except for this issue) test link here
$('.editableContact').editable(
function(value, settings) {
jQuery.ajax({
'type':'POST',
'url':'/test/update.php',
'data':$(this).attr('id')+'='+value,
'cache':false,
'success':function(rjson) {
//r=JSON.parse(rjson);
//console.log(r);
//We could do a hacky solution here to over-write the cell data, requiring another lookup on the server when posting.
}
});
return 'Display of Selected Option (value is:'+value+')';
//normal return: return(value);
//None of these work:
//return $(this).html(settings.data[value]);
//return settings.data[value];
//jQuery.parseJSON(settings.data)[value];
},
{
placeholder:'Double Click to Edit',
submit : 'save',
cancel : 'x',
event : 'dblclick',
type : 'select',
loadurl : '/test/getContactsJson.php'
});
Any help is appreciated - thank you!

change some tinymce behaviour (javascript)

Hi everybody
I am using the tinymce format dropdown to apply custom styles to html elements. This is for users without html knowledge
One annoying thing for me is that when a user klicks at different styles they all get added and something like this may happen
<div class="floatleft floatright positionup positiondown">
In order to prevent this I searched for the responsible code which is in editor_template.js (compressed) but visible in editor_template_src.js
Is there maybe a way to rewrite this piece of javascript so that each applied style replaces the former?
_createStyleSelect : function(n) {
var t = this, ed = t.editor, ctrlMan = ed.controlManager, ctrl;
// Setup style select box
ctrl = ctrlMan.createListBox('styleselect', {
title : 'advanced.style_select',
onselect : function(name) {
var matches, formatNames = [];
each(ctrl.items, function(item) {
formatNames.push(item.value);
});
ed.focus();
ed.undoManager.add();
// Toggle off the current format
matches = ed.formatter.matchAll(formatNames);
if (!name || matches[0] == name)
ed.formatter.remove(matches[0]);
else
ed.formatter.apply(name);
ed.undoManager.add();
ed.nodeChanged();
return false; // No auto select
}
});
How about:
if (!name || matches[0] == name)
ed.formatter.remove(matches[0]);
else
ed.formatter.remove(matches[0]);
ed.formatter.apply(name);
Just a wild guess, haven't tried it myself.
This a lot of work to do, but it can be done.
I solved this issue writing a custom plugin and using a custom FormatterClass.
I suggest you try developing with tiny_mce_dev.js - this way you are able to track down problems to js classes.
Then you should have a look at the js-class Formatter.js and try to modify this one in order to fullfill your wishes.
The next step will be to save the mofied Formatter.js and make it part of your plugin, so that you can reset the real Formatter.js, cause i suggest not to change the tinymce core files.

Categories