Knockout .js with jQuery UI slider - jquery-ui

Say I have the following jQuery UI sliders that are linked to a textbox.
Is it possible to allow the user to enter values in the textbox that are greater than the sliders value (and set the slider to max)?
ko.bindingHandlers.slider = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || {};
$(element).slider(options);
ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
ko.utils.registerEventHandler(element, "slide", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (isNaN(value)) value = 0;
$(element).slider("value", value);
}
};
In this example: http://jsfiddle.net/jearles/Dt7Ka/12/ I would like to be able to save values over 100 in the textboxes and have the sliders appear at their max value.

You can do with only updating the observable value in your slidechange event if the observable's value is less then options.max:
ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
var observable = valueAccessor();
var currentMax = $(element).slider("option", "max");
if (observable() <= currentMax)
observable(ui.value);
});
JSFiddle demo.

Put this lines after the line: if (isNaN(value)) value = 0; at the binding update function
if(value>100){
$(element).slider("option","max",value);
}
Example:
http://jsfiddle.net/Razaz/Qy6jR/4/
It changes the maximum value of the slider to the new value entered in the textbox if the value is greater than 100
Greetings.

Related

How to bind jQuery UI option to a Knockout observable

This fiddle shows how to bind a jQuery slider 'slide' event to a Knockout observable. How would this need to change to also bind the 'max' option of the slider to an observable? Do you have to create an entirely new ko.bindingsHandler entry? Or can the existing one be used?
Here is the code from the fiddle for reference.
HTML
<h2>Slider Demo</h2>
Savings: <input data-bind="value: savings, valueUpdate: 'afterkeydown'" />
<div style="margin: 10px" data-bind="slider: savings, sliderOptions: {min: 0, max: 100, range: 'min', step: 1}"></div>
Spent: <input data-bind="value: spent, valueUpdate: 'afterkeydown'" />
<div style="margin: 10px" data-bind="slider: spent, sliderOptions: {min: 0, max: 100, range: 'min', step: 1}"></div>
Net: <span data-bind="text: net"></span>
JS
ko.bindingHandlers.slider = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || {};
$(element).slider(options);
ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
ko.utils.registerEventHandler(element, "slide", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (isNaN(value)) value = 0;
$(element).slider("value", value);
}
};
var ViewModel = function() {
var self = this;
self.savings = ko.observable(10);
self.spent = ko.observable(5);
self.net = ko.computed(function() {
return self.savings() - self.spent();
});
}
ko.applyBindings(new ViewModel());
Look at this fiddle. I added checking if max is observable and subscribing to it:
if (ko.isObservable(options.max)) {
options.max.subscribe(function(newValue) {
$(element).slider('option', 'max', newValue);
});
options.max = ko.utils.unwrapObservable(options.max);
}
I have a collection of jQUery Ui bindings for KO. I havent done the slider because I havent needed that control in a project. But check my button binding
https://github.com/AndersMalmgren/Knockout.Bindings
ko.bindingHandlers.button = {
initIcon: function (options) {
if (options.icon) {
options.icons = { primary: options.icon };
}
},
init: function (element, valueAccessor) {
var options = ko.utils.unwrapObservable(ko.toJS(valueAccessor())) || {};
ko.bindingHandlers.button.initIcon(options);
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).button("destroy");
});
$(element).button(options);
},
update: function (element, valueAccessor) {
var options = ko.toJS(valueAccessor());
ko.bindingHandlers.button.initIcon(options);
if (options) {
$(element).button(options);
}
}
};
The magic is done in the update function, KO will by default subscribe to all observables in a object literal, so if you bind to { max: aObservable } the update function will trigger when any child updates.
I then do ko.toJS(valueAccessor()); to un observify the object and use that to update the jQuery control. This method can be used for slider as well, its generic and you do not need to add extra code for each setting

knockout observable array bounded listview doesnt get rendered in JQM

JQM listview get populated as with the data with no issue as expected, but i cant get it rendered with JQM styles. could any one can help me with this issue.
I have tried with listview(), listview("refresh"), trigger("create") none of them did work
var ProfessionsModel = function() {
var self = this;
self.professionDetails = ko.observableArray([]);
self.getProfessionDetails=function(){
var rest = new RestService('${pageContext.request.contextPath}/rest/profession/designations');
rest.findAll(function(data) {
$.each(data, function(index, value){
self.professionDetails.push(value);
});
});
};
self.removeProfessionDetails= function(){
self.professionDetails.removeAll();
};
};
var pm = new ProfessionsModel();
$('#profession').live('pagecreate', function(event) {
ko.applyBindings(pm, this);
});
$('#profession').live('pagebeforeshow', function(event) {
pm.removeProfessionDetails();
});
$('#profession').live('pageshow', function(event) {
pm.getProfessionDetails();
$('#profession').find("ul").listview();
$('#profession').find("ul").listview("refresh");
});
You are doing it in a wrong moment. You want believe how jQM is picky about a right moment.
var ProfessionsModel = function() {
var self = this;
self.professionDetails = ko.observableArray([]);
self.getProfessionDetails=function(){
var rest = new RestService('${pageContext.request.contextPath}/rest/profession/designations');
rest.findAll(function(data) {
$.each(data, function(index, value){
self.professionDetails.push(value);
});
$('#profession').find("ul").listview();
$('#profession').find("ul").listview("refresh");
});
};
self.removeProfessionDetails= function(){
self.professionDetails.removeAll();
};
};
jQM trigger refresh will brake if not executed after content has been appended, hence refresh after $.each part.

Using knockout js with jquery ui sliders

I'm trying to figure out if knockout js would work nicely for the following problem:
I have multiple sliders that I want to link to textboxes.
When the textbox is changed the corresponding slider must update to the new value and vice versa.
On changing the slider value or textbox a function needs to be called that uses the input from all textboxes to calculate a result.
I have my quick and dirty jQuery solution here.
Would it be easy to achieve the same result in a more elegant way using knockout js?
I guess I would need to create a custom binding handler like its done in jQuery UI datepicker change event not caught by KnockoutJS
Here is an example: http://jsfiddle.net/jearles/Dt7Ka/
I use a custom binding to integrate the jquery-ui slider and use Knockout to capture the inputs and calculate the net amount.
--
UI
<h2>Slider Demo</h2>
Savings: <input data-bind="value: savings, valueUpdate: 'afterkeydown'" />
<div style="margin: 10px" data-bind="slider: savings, sliderOptions: {min: 0, max: 100, range: 'min', step: 1}"></div>
Spent: <input data-bind="value: spent, valueUpdate: 'afterkeydown'" />
<div style="margin: 10px" data-bind="slider: spent, sliderOptions: {min: 0, max: 100, range: 'min', step: 1}"></div>
Net: <span data-bind="text: net"></span>
View Model
ko.bindingHandlers.slider = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || {};
$(element).slider(options);
$(element).slider({
"slide": function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
},
"change": function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
}
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
},
update: function (element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
if (isNaN(value)) {
value = 0;
}
$(element).slider("value", value);
}
};
var ViewModel = function() {
var self = this;
self.savings = ko.observable(10);
self.spent = ko.observable(5);
self.net = ko.computed(function() {
return self.savings() - self.spent();
});
}
ko.applyBindings(new ViewModel());
I know it's some days ago but I made a few adjustments to John Earles code:
ko.bindingHandlers.slider = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || {};
$(element).slider(options);
ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
ko.utils.registerEventHandler(element, "slide", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (isNaN(value)) value = 0;
$(element).slider("option", allBindingsAccessor().sliderOptions);
$(element).slider("value", value);
}
};
The reason for this is that if you use options that change (fx another observable) then it won't affect the slider even if you wanted it to do so.
#John Earles and #Michael Kire Hansen: thanks for your wonderful solutions!
I used the advanced code from Michael Kire Hansen. I tied the "max:" option of the slider to a ko.observable and it turned out that the slider does not correctly update the value in this case. Example: Lets say the slider is at value 25 of max 25 und you change the max value to 100, the slider stays at the most right position, indicating that it is at the max value (but value is still 25, not 100). As soon as you slide one point to the left, you get the value updated to 99.
Solution:
in the "update:" part just switch the last two lines to:
$(element).slider("option", allBindingsAccessor().sliderOptions);
$(element).slider("value", value);
This changes the options first, then the value and it works like a charm.
Thanks so much for the help, I needed to use a range slider in my scenario so here is an extension to #John Earles and #Michael Kire Hansen
ko.bindingHandlers.sliderRange = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || {};
$(element).slider(options);
ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
var observable = valueAccessor();
observable.Min(ui.values[0]);
observable.Max(ui.values[1]);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
ko.utils.registerEventHandler(element, "slide", function (event, ui) {
var observable = valueAccessor();
observable.Min(ui.values[0]);
observable.Max(ui.values[1]);
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (isNaN(value.Min())) value.Min(0);
if (isNaN(value.Max())) value.Max(0);
$(element).slider("option", allBindingsAccessor().sliderOptions);
$(element).slider("values", 0, value.Min());
$(element).slider("values", 1, value.Max());
}
};
and then the HTML to accompany it
<div id="slider-range"
data-bind="sliderRange: { Min: 0, Max: 100 },
sliderOptions: {
range: true,
min: 0,
max: 100,
step: 10,
values: [0, 100]
}"></div>

Jquery UI autocomplete select

I need some help with the code below.
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push(val.name);
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.value);
}
});​
using FireBug, i'm getting this in my console :
jQuery171003666625335785867_1337116004522([{"name":"97300
Cayenne","zzz":"203"},{"name":"97311
Roura","zzz":"201"},{"name":"97312 Saint
Elie","zzz":"388"},{"name":"97320 Saint Laurent du
Maroni","zzz":"391"},{"name":"97351
Matoury","zzz":"52"},{"name":"97354 Remire MontJoly
Cayenne","zzz":"69"},{"name":"97355 Macouria Tonate","zzz":"449"}])
Everything is working very fine, but I don't know how to get the value of 'zzz' on select item.
I tried
alert(ui.item.zzz);
But it doesn't work.
The autocomplete widget expects a data source in array format with either:
Objects containing a label property, a value property, or both
Simple string values
You are currently building up the second (an array of string values), which works fine, but you can also slightly tweak your data as you iterate over it and also supply the other properties in the object:
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push({
label: val.name,
zzz: val.zzz
});
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.zzz);
}
});​
Now, since the array you're supplying the widget contains objects with a name property, you should get autocomplete functionality and also gain access to the zzz property.
Here's a working example (without the AJAX call): http://jsfiddle.net/LY42X/
You're source function is only populating the name. If you want everything from that data structure, do this:
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push(val); //not val.name
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.value.zzz);
}
});​
This seems to be an array of objects... what your may be missing is the "[0]" or in general "[index]".
Please check this: jqueryui.com/demos/autocomplete/#event-select

jquery ui slider, stop sliding if certain conditions are met

Using the jQuery UI Slider, I'm trying to figure out how to make it so that the slider stops working once certain conditions are met. Any ideas? I thought stopping event propogation in the "start" part would work, but ...it doesn't. So I'm still clueless and lost.
<script type="text/javascript">
$(document).ready(function () {
var spendable = 1000;
var spent = 0;
function spend(quantity) {
var remaining = spendable - quantity;
$('#spendable').text(remaining);
}
$("#eq .slider").each(function () {
var current = 0;
$(this).slider({
range: "min",
step: 100,
value: 0,
min: 0,
max: 500,
animate: true,
orientation: "horizontal",
start: function (event, ui) {
if (spent < spendable)
return true;
event.stopPropagation();
},
slide: function (event, ui) {
// set the current value to whatever is selected.
current = ui.value;
$(this).parent('div:eq(0)').find('.spent').text(current);
var totalled = 0;
$("#eq .slider").each(function () {
totalled += parseInt($(this).parent('div:eq(0)').find('.spent').text());
spend(totalled);
});
}
});
});
Try:
.....
slide: function (event, ui) {
// set the current value to whatever is selected.
current = ui.value;
if(current > 300){
current = 300; //otherwise, it's stuck at 301
return false;
}
....rest of your code

Resources