dynamic radio button behaviour with knockout js - javascript

I have a button to create radio buttons like this:
<input value="&uparrow;" type="button" data-bind=" click: moveUp"/>
<input value="&downarrow;" type="button" data-bind="click: moveDown"/>
<input data-bind="value: selectedradio" />
<div data-bind="foreach: radios">
<div data-bind="attr:{id:radioid} ">
<input type="radio" name="group" data-bind="value:radioid, checked:$parent.selectedradio"/>
</div>
</div>
<div>
<input type="button" value="+" data-bind="click: addRadio"/>
</div>
when the radio buttons are created they are each assigned a unique index and i have bound the checked attribute to a property on the parent called selectedradio
I am able to modify selectedradio though an html input and the selected radio will change but If I modify the value progmmatically it will not.
I created a fiddle here: http://jsfiddle.net/8vVeU/
here is the javascript for reference:
function Radio(id){
this.radioid = ko.observable(id);
}
function ViewModel() {
var self = this;
self.selectedradio = ko.observable(0);
self.radios = ko.observableArray([new Radio(0),new Radio(1),new Radio(2),new Radio(3)]);
self.addRadio = function() {
self.radios.push(new Radio());
self.reIndex();
};
self.moveUp = function() {
self.selectedradio(self.selectedradio()-1)
self.reIndex();
};
self.moveDown = function() {
self.selectedradio(self.selectedradio()+1)
self.reIndex();
};
self.reIndex = function() {
$.each(self.radios(), function(i, r) {
r.radioid(i);
});
}
}
ko.applyBindings(new ViewModel());
How can I resolve this issue?

In the case of radio buttons the checked binding by default compares the input's value attribute - which is a string - to the model property.
So you need to store strings in your selectedradio :
self.moveUp = function(r) {
r=parseInt(r,10);
self.selectedradio((parseInt(self.selectedradio())-1).toString())
self.reIndex();
};
self.moveDown = function(r) {
r=parseInt(r,10);
self.selectedradio((parseInt(self.selectedradio())+1).toString())
self.reIndex();
};
It works with the textbox because it will fill in the selectedradio with the entered string.
Demo JSFiddle.
Or you can change the default behavior and you can tell KO to use a different property as the checkbox's value with the checkedValue option:
<input type="radio" name="group" data-bind="value:radioid,
checked:$parent.selectedradio, checkedValue: radioid"/>
In this case you don't need to alter your moveUp and moveDown methods because now the selectedradio will always contain integers however because your textbox still sets the selectedradio to string it won't work any more.
Demo JSFiddle.

Related

Radio buttons bound to knockout computed

I have some problems with knockoutjs writables computes observables I think.
I created a fiddle.
What I need is actually not so hard:
I have the nullable WeightInGramms and VolumeInMilliliters values.
These values should be bound to two input fields (only one of them should be visible).
At the top, the user can choose which of these values he want to use with the radio buttons.
At initialisation, when both of them are null, the "g" radio button should be checked, also when WeightInGramms is not null. When VolumeInMilliliters have some value, the "ml" radio button should be checked.
I used a knockoutjs writable computes observable for this, please correct me if there is a better way to do this!
So, the read function seems to work, when I change the value in the input which are bind to WeightInGramms or VolumeInMilliliters. But when I change the radio buttons nothing happens...
var ViewModel = function (data) {
var self = this;
this.VolumeInMilliliters = ko.observable(data.VolumeInMilliliters);
this.WeightInGramms = ko.observable(data.WeightInGramms);
this.GrammIsSelected = ko.computed({
read: function() {
return (!self.WeightInGramms() && !self.VolumeInMilliliters()) || !self.VolumeInMilliliters();
},
write: function (newValue) {
console.log(newValue);
return newValue;
},
owner: this
});
};
When I change the radio buttons, the corresponding input field should be visible:
<div data-bind="visible: GrammIsSelected">g is active</div>
<div data-bind="visible: !GrammIsSelected()">ml is active</div>
Edit:
When the Form is loaded for the first Time both values will be null -> the "g" button should be checked.
The observables can be initialized with:
null, null
33, null
null, 33
Both can be null, but only one of them can have a value.
If the user types in a value, and then clicks the other radio the value can be applied to the other value.
I hop it is a bit clearer
Some tips:
Make your viewModel (JS) resemble the view (HTML) as much as possible. Additionally, this avoids having to repeat too much markup. In this case, radio buttons are always lists, and so it is most convenient to store the options in an array.
Instead of testing whether GrammIsselected, you should define a selected observable that holds the selected metric. This way if you ever add more options, the code will still work without refactoring.
When to use a computed property? A computed property adds readonly value by calculating a result based on multiple observables/ variables. A writeable computed property does the same, except you can write back changes. This makes it especially useful for 'Select all' style checkboxes (see example 2 in the docs), data validation & transformations.
The absolutely clearest setup for what you want to achieve would be the following:
var ViewModel = function (data) {
this.metrics = [
{ name: 'g', value: ko.observable(data.WeightInGramms) },
{ name: 'ml', value: ko.observable(data.VolumeInMilliliters) }
];
this.selectedMetric = ko.observable(this.metrics[0]);
};
By setting an object as observable (selectedMetric), you can furthermore simplify the markup for the volume/weight input:
<div class="control-group">
<label class="control-label">choose</label>
<div class="controls" data-bind="with: selectedMetric">
<input type="text" data-bind="value: value">
<span class="help-inline" data-bind="text: '(' + name + ')'"></span>
</div>
</div>
Getting the 'final value' of your app would be as easy as retrieving selectedMetric().value().
A computed property isn't super useful here, but for example, if you wanted to provide a way for the user to both set the g/ml with radio buttons and text, you could add the following method to your viewModel:
this.selectedMetricByText = ko.computed({
read: function() {
return this.selectedMetric().name;
},
write: function(value) {
var newMetric = ko.utils.arrayFirst(this.metrics, function(metric) {
return metric.name === value;
}) || false;
this.selectedMetric(newMetric || this.metrics[0]);
}
}, this);
Fiddle
Your write function doesn't write anything, it seems?
Contrary to this other answer, based on my experience I'll give you the advice not to avoid writeable computeds: used wisely they can be very effective!
Note: in my answer I try to remain close to the original design from the question, but if you're able (have resources available) I recommend redesigning things even more based on the answer by #Tyblitz.
Here's the way you could approach this utilizing a computed:
var ViewModel = function (data) {
var self = this;
self.VolumeInMilliliters = ko.observable(data.VolumeInMilliliters);
self.WeightInGramms = ko.observable(data.WeightInGramms);
var _measurementType = ko.observable("volume");
self.MeasurementType = ko.computed({
read: function() {
return _measurementType();
},
write: function (newValue) {
_measurementType(newValue);
self.VolumeInMilliliters(newValue === "volume" ? 0 : null);
self.WeightInGramms(newValue === "mass" ? 0 : null);
}
});
};
ko.applyBindings(new ViewModel({ VolumeInMilliliters: 12 }));
label { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<label>
<input type="radio" name="measurementType" value="volume" data-bind="checked: MeasurementType">
Volume
</label>
<input data-bind="value: VolumeInMilliliters, enable: MeasurementType() === 'volume'">
<label>
<input type="radio" name="measurementType" value="mass" data-bind="checked: MeasurementType">
Weight in gramms
</label>
<input data-bind="value: WeightInGramms, enable: MeasurementType() === 'mass'">
For radio buttons, you need to use the "checked" binding.
http://knockoutjs.com/documentation/checked-binding.html
And for my personal experience (as a KO nija) I have to give you the advice: avoid writeable ko computed.
<input type="radio" name="unitSelector" value="g" data-bind="checked: unit" /> Grams</br>
<input type="radio" name="unitSelector" value="ml" data-bind="checked: unit" /> Millis</br>
Now the view model
var ViewModel = function (data) {
var self = this;
self.unit = ko.observable('g');
self.userValue = ko.observable(data.WeightInGramms);
};
Now the binding should only care about the value entered by the user, you don't need computed here and you don't need two fields...
<input type="text" data-bind="textInput: userValue ">
<span data-bind="text: unit"> </span>
It looks really too simple but that's what you need, as #Jotabe mentioned, you should take measurement and the unit as two separate things... what you do with this thing later, could be done with computed observables.
If this thing doesn't solve your problem then you should tell what you really want...

knockout - computed observable with parameter working only on alternate clicks

I have a main checkbox, clicking on which all the checkboxes are checked. For the child checkboxes, I have some different logic involving their computation from 2 different observables besides the mainCheckBox and when child checkboxes are checked, the value needs to be written to different observables.
I have created a computed observable with parameter as below:
var vm = ko.mapping.fromJS(data);
var viewModel =
function ()
{
this.self = this;
this.ExportSchemas = vm;
this.SelectAll = ko.observable(true);
this.IsChecked = function (checkboxVM) {
return ko.computed({
read: function () {
return this.SelectAll(); //problemLine
},
write: function (value) {
checkboxVM.Selected(value);
alert(checkboxVM.Selected());
},
owner: this.self
});
};
};
<input type="checkbox" data-bind="checked: SelectAll" value="None" id="mainCheckBox" name="check" />
<div data-bind="foreach: ExportSchemas">
<div data-bind="foreach: Clauses">
<input type="checkbox" value="None" data-bind="checked: $root.IsChecked($data), attr: { id: 'clause' + Id(), value: Id() }" name="check" />
</div>
</div>
The write behavior of computed observable is weird, it works on alternate clicks when the problemLine in above code is as written above. And when I use the following instead for problemLine:
return this.SelectAll;
Then the write of computed observable works properly, but the the read stops working and checking/unchecking mainCheckBox has no effect on child check boxes.
Any suggestions?

DataPicker not getting binded to textbox ? fiddle provided

Well in other cases i will get datepicker binded to my textbox which will be straight forward but not in this case .
Fiddle link : http://jsfiddle.net/JL26Z/1/ .. while to setup perfect seanrio i tried but unable to bind datepicker to textboxes . except that everything is in place
My code :
**<script id="Customisation" type="text/html">** // here i need to have text/html
<table style="width:1100px;height:40px;" align="center" >
<tr>
<input style="width:125px;height:auto;" class="txtBoxEffectiveDate" type="text" id="txtEffective" data-bind="" />
</tr>
</script>
The above code is used for my dynamic generation of same thing n no of time when i click each time on a button . So above thing is a TEMPLATE sort of thing .
My knockout code :
<div data-bind="template:{name:'Customisation', foreach:CustomisationList},visible:isVisible"></div>
<button data-bind="click:$root.CustomisatioAdd" >add </button>
I tried same old way to bind it with datepicker
$('#txtEffective').datepicker(); // in document.ready i placed
Actually to test this i created a textbox with some id outside script with text/html and binded datepicker to it and It is working fine sadly its not working for the textbox inside text/html and i want to work at any cost.
PS: well i haven't posted my view model as it is not required in this issue based senario
View model added with Js
var paymentsModel = function ()
{
function Customisation()
{
var self = this;
}
var self = this;
self.isVisible = ko.observable(false);
self.CustomisationList = ko.observableArray([new Customisation()]);
self.CustomisationRemove = function () {
self.CustomisationList.remove(this);
};
self.CustomisatioAdd = function () {
if (self.isVisible() === false)
{
self.isVisible(true);
}
else
{
self.CustomisationList.push(new Customisation());
}
};
}
$(document).ready(function()
{
$('#txtEffective').datepicker();
ko.applyBindings(new paymentsModel());
});
Any possible work around is appreciated
Regards
The best way I've found to do this is create a simple bindingHandler.
This is adapted from code I have locally, you may need to tweak it...
** code removed, see below **
Then update your template:
** code removed, see below **
By using a bindingHandler you don't need to try to hook this up later, it's done by knockout when it databinds.
Hope this is helpful.
EDIT
I created a fiddle, because I did indeed need to tweak the date picker binding quite a lot. Here's a link to the Fiddle, and here's the code with some notes. First up, the HTML:
<form id="employeeForm" name="employeeForm" method="POST">
<script id="PhoneTemplate" type="text/html">
<div>
<span>
<label>Country Code:</label>
<input type="text" data-bind="value: countryCode" />
</span>
<span><br/>
<label>Date:</label>
<input type="text" data-bind="datepicker: date" />
</span>
<span>
<label>Phone Number:</label>
<input type="text" data-bind="value: phoneNumber" />
</span>
<input type="button" value="Remove" data-bind="click: $parent.remove" />
</div>
</script>
<div>
<h2>Employee Phone Number</h2>
<div data-bind="template:{name:'PhoneTemplate', foreach:PhoneList}">
</div>
<div>
<input type="button" value="Add Another" data-bind="click: add" />
</div>
</div>
</form>
Note I removed the id=... from in your template; because your template repeats per phone number, and ids must be unique to be meaningful. Also, I removed the datepicker: binding from the country code and phone number elements, and added it only to the date field. Also - the syntax changed to "datepicker: ". If you need to specify date picker options, you would do it like this:
<input type="text" data-bind="datepicker: myObservable, datepickerOptions: { optionName: optionValue }" />
Where optionName and optionValue would come from the jQueryUI documentation for datepicker.
Now for the code and some notes:
// Adapted from this answer:
// https://stackoverflow.com/a/6613255/1634810
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {},
observable = valueAccessor(),
$el = $(element);
// Adapted from this answer:
// https://stackoverflow.com/a/8147201/1634810
options.onSelect = function () {
if (ko.isObservable(observable)) {
observable($el.datepicker('getDate'));
}
};
$el.datepicker(options);
// set the initial value
var value = ko.unwrap(valueAccessor());
if (value) {
$el.datepicker("setDate", value);
}
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$el.datepicker("destroy");
});
},
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
$el = $(element);
//handle date data coming via json from Microsoft
if (String(value).indexOf('/Date(') === 0) {
value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
}
var current = $el.datepicker("getDate");
if (value - current !== 0) {
$el.datepicker("setDate", value);
}
}
};
function Phone() {
var self = this;
self.countryCode = ko.observable('');
self.date = ko.observable('');
self.phoneNumber = ko.observable('');
}
function PhoneViewModel() {
var self = this;
self.PhoneList = ko.observableArray([new Phone()]);
self.remove = function () {
self.PhoneList.remove(this);
};
self.add = function () {
self.PhoneList.push(new Phone());
};
}
var phoneModel = new PhoneViewModel();
ko.applyBindings(phoneModel);
Note the very updated binding handler which was adapted from this answer for the binding, and this answer for handling onSelect.
I also included countryCode, date, and phoneNumber observables inside your Phone() object, and turned your model into a global variable phoneModel. From a debugger window (F12 in Chrome) you can type something like:
phoneModel.PhoneList()[0].date()
This will show you the current value of the date.
I notice that your form is set up to post somewhere. I would recommend instead that you add a click handler to a "Submit" button and post the values from your phoneModel using ajax.
Hope this edit helps.
Dynamic entities need to have datepicker applied after they are created. To do this I'd use an on-click function somewhere along the lines of
HTML
<!-- Note the id added here -->
<button data-bind="click:$root.CustomisatioAdd" id="addForm" >add </button>
<script>
$(document).on('click', '#addForm', function(){
$('[id$="txtEffective"]').datepicker();
});
</script>

Issue in getting index value

I am trying to store value in attribute in input tag which would like as follows.
The following code will repeat several times and the value for different radio can be saved using index.
<div data-bind="attr : { name : 'ex['+$index()+']' }>
<input type="radio" name="value" data-target="#modal" data-bind="click:fun.fill($index())"/>
</div>
From the above text box i can get the index of that input.And it points to a common modal function from bootstrap which opens a popup.
<div class="modal fade">
<select data-bind="attr:{name:'assignedResources['+$index()+'][repeatedType]'},
options : $root.repeats,value : repeatedType"></select>
</div><!-- /.modal -->
This is a sample of modal target.I want to call this modal as common.(i.e)it will be called from several places.I want to show appropriate popup for appropriate click from radio button.
But what i get is value of last index.Thats my problem
I'm not 100% sure I understand your question, but something like this...
this.abc = ko.observable('');
this.fun = {
var that = this;
fill: function(index) {
console.log(that.abc());
}
}
As far as I understand your problem, you need an observable to store your value, and then you can access it by any other function on your viewModel.
This is a jsFiddle with my initial approach, let me know if is what you needed or clarify instead:
http://jsfiddle.net/rdarioduarte/X8Rc4/
With a model like this:
var viewModel = function() {
this.abc = ko.observable('Value to store');
this.fun = function() {
alert(this.abc());
}
}
ko.applyBindings(new viewModel());
Thanks,
Dario
I do not quite understand about your question. But, maybe this may help:
1) Obtains index of your input element automatically on page load to viewModel function maybe need custom binding to handle that:
e.g custom binding:
ko.bindingHandlers.saveIndex = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var index = ko.utils.unwrapObservable(valueAccessor());
viewModel.fun(index); // accessing fun function on viewModel
// You can also access that function using bindingContext.$root
// bindingContext.$root.fun(index);
}
};
e.g html:
<input type="text" data-bind="saveIndex: $index()"/>
2) Store index to input value attribute using attr binding:
<input type="text" data-bind="attr: { value: $index() }">
3) Send your input attr value to viewModel function onClick:
<input type="text" value="thisIsExampleValue" data-bind="click: function() { $root.fun($element.value); }">
You also can use event binding for this behavior, Knockout.Event-binding
UPDATE:
Try this:
<div data-bind="attr : { name : 'ex['+$index()+']' }>
<input type="radio" name="value" data-target="#modal" data-bind="click: function() { fun.fill($index()) }"/>

Passing jQuery objects to a function

Here is the working demo of what I want to achieve. Just enter some value in input and you might get what I want to achieve. (Yes, I got it working but stay on..)
But it fails when multiple keys are pressed together.
What I am trying :
I have screen which contains few enabled and few disabled input elements. Whenever user updates any value in editable input element, I want to update disabled input which had same value with user updated value.
HTML :
<input value="foo" /> // When User updates this
<br/>
<input value="bar">
<br/>
<input value="Hello">
<br/>
<input value="World">
<br/>
<input value="foo" disabled> // this should be updated
<br/>
<input value="bar" disabled>
<br/>
<input value="foo" disabled> // and this also
<br/>
<input value="bar" disabled>
<br/>
<input value="Happy Ending!">
<br/>
I tried this which I think will save me from multiple_clicks_at_a_time
JS:
$(":input:not(:disabled)").keyup(function () {
// Get user entered value
var val = this.value;
// Find associated inputs which should be updated with new value
siblings = $(this).data("siblings");
$(siblings).each(function () {
// Update each input with new value
this.value = val;
});
});
$(function () {
$(":input:not(:disabled)").each(function () {
// Find inputs which should be updated with this change in this input
siblings = $(":input:disabled[value=" + this.value + "]");
// add them to data attribute
$(this).data("siblings", siblings);
});
});
But I am not able to pass the selectors to keyup function and invoke .each on it.
PS:
My previous completely different try, working with single_click_at_a_time but I felt that I am unnecessarily traversing the DOM again and again so dropped this
$(":input").keypress(function () {
$(this).data("oldVal", this.value);
});
$(":input").keyup(function () {
var oldVal = $(this).data("oldVal");
$(this).data("newVal", this.value);
var newVal = $(this).data("newVal");
$("input:disabled").each(function () {
if (this.value == oldVal) this.value = newVal;
});
});
I would group those inputs first and bind a handler for enabled elements to apply to the group. See below,
var grpInp = {};
$(":input").each(function () {
if (grpInp.hasOwnProperty(this.value)) {
grpInp[this.value] = grpInp[this.value].add($(this));
} else {
grpInp[this.value] = $(this);
}
});
$.each(grpInp, function (i, el) {
el.filter(':enabled').keyup(function () {
el.val(this.value);
});
});
DEMO: http://jsfiddle.net/fjtFA/9/
The above approach basically groups input element with same value, then filters them based on :enabled and bind a handler to apply it to the group.
// Find associated inputs which should be updated with new value
siblings = $(this).data("siblings", siblings);
No. The .data method called with two arguments does not get, but set the data (and returns the current selection). Also, you should make your variables local:
var siblings = $(this).data("siblings");
Working demo

Categories