I want to populate multiple inputs inside a template after select of an autocomplete item. I'm following http://jsfiddle.net/rniemeyer/MJQ6g/ but not sure how to apply this to multiple inputs.
Model:
<script>
var ContactModel = function (contactsInfo) {
var self = this;
self.Company = ko.observable();
self.ContactsInformation = contactsInfo;
self.Name = ko.observable();
};
var ContactsInformationModel = function () {
var self = this;
self.Address1 = ko.observable();
};
var viewModel;
var ViewModel = function () {
var self = this;
self.Contact1 = new ContactModel(new ContactsInformation);
self.Contact2 = new ContactModel(new ContactsInformation);
};
$(function () {
viewModel = new ViewModel();
ko.applyBindings(viewModel);
});
function getContacts(searchTerm, sourceArray) {
$.getJSON("web_service_uri" + searchTerm, function (data) {
var mapped = $.map(data, function (item) {
return {
label: item.Name,
value: item
};
});
return sourceArray(mapped);
});
}
</script>
Template:
<script type="text/html" id="contact-template">
<div>
Name
<input data-bind="uniqueName: true,
jqAuto: { autoFocus: true, html: true },
jqAutoSource: $root.Contacts,
jqAutoQuery: getContacts,
jqAutoValue: Name,
jqAutoSourceLabel: 'label',
jqAutoSourceInputValue: 'value',
jqAutoSourceValue: 'label'"
class="name" />
</div>
<div>
Company
<input data-bind="value: Company, uniqueName: true" class="company" />
</div>
<div>
Address
<input data-bind="value: ContactsInformation.Address1, uniqueName: true" class="address1" />
</div>
</script>
Html:
<div data-bind="template: { name: 'contact-template', data: Contact1 }">
</div>
<hr/>
<div data-bind="template: { name: 'contact-template', data: Contact2 }">
</div>
If you leave out the jqAutoSourceValue option from your data-bind, then it will set the value equal to the actual object. Then, you can read properties off of that object.
Usually, you would have an observable like: mySelectedPerson and then bind a section (possibly with the with binding) against it and access the individual properties/observables off of that object.
Here is the sample modified to leave out the jqAutoSourceValue option, bind jqAutoValue against an observable called mySelectedPerson and use the with binding to display some properties from the selected object. http://jsfiddle.net/rniemeyer/YHvyL/
Related
I'm trying to find a way to use Devextreme RadioGroup js widget with ASP.NET Core.
I've created this simple View:
<form asp-action="SelectSourceData" asp-controller="Home" method="post">
<div class="form-group">
<label for="rg-mode">Please Choose Migration Mode</label>
<div id="rg-mode"></div>
</div>
<button type="submit" class="btn btn-primary">Proceed</button>
</form>
#section Scripts {
<script>
$(function () {
$("#rg-mode").dxRadioGroup({
dataSource: modes,
displayExpr: "text",
valueExpr: "val",
value: "by-org"
})
});
var modes = [
{ text: "By Organisation", val: "by-org" },
{ text: "By Contract Type", val: "by-contr" },
{ text: "By Employee", val: "by-emp" },
{ text: "Mixed Mode", val: "mm" }
];
</script>
}
When user presses Proceed button SelectSourceData action method is invoked:
[HttpPost]
public ViewResult SelectSourceData(string val)
{
// get selected value here ... ?
return View();
}
My question is: is it possible to somehow obtain the value selected in dxRadioGroup widget?
Following #Stephen's advice I added a hidden input field:
<div class="form-group">
<input id="hdnMode" name="mode" type="hidden" value="by-org" class="form-control" />
<label for="rg-mode">Please Choose Migration Mode</label>
<div id="rg-mode"></div>
</div>
and registered a handling function for value changed event:
$(function () {
$("#rg-mode").dxRadioGroup({
dataSource: modes,
displayExpr: "text",
valueExpr: "val",
value: "by-org",
onValueChanged: function (e) {
var previousValue = e.previousValue;
var newValue = e.value;
// Event handling commands go here
$("#hdnMode").val(newValue);
}
})
});
The action method now correctly obtains the value submitted by the form:
[HttpPost]
public ViewResult SelectSourceData(string mode)
{
// mode argument successfully set to submitted value
var t = mode;
....
Getting started with knockout, I have been playing with the pattern found at http://knockoutjs.com/examples/cartEditor.html. I have cascading select menus where the second one's options depend on the state of the first -- no problem so far. But whatever I do, I haven't figured a way to change the out-of-the-box behavior whereby the second element is not visible -- not rendered, I would imagine -- until the first element has a true-ish value (except by taking out the optionsCaption and instead stuffing in an empty record at the top of my data -- more on that below.) The markup:
<div id="test" class="border">
<div class="form-row form-group">
<label class="col-form-label col-md-3 text-right pr-2">
language
</label>
<div class="col-md-9">
<select class="form-control" name="language"
data-bind="options: roster,
optionsText: 'language',
optionsCaption: '',
value: language">
</select>
</div>
</div>
<div class="form-row form-group">
<label class="col-form-label col-md-3 text-right pr-2">
interpreter
</label>
<div class="col-md-9" data-bind="with: language">
<select class="form-control" name="interpreter"
data-bind="options: interpreters,
optionsText : 'name',
optionsCaption: '',
value: $parent.interpreter"
</select>
</div>
</div>
</div>
Code:
function Thing() {
var self = this;
self.language = ko.observable();
self.interpreter = ko.observable();
self.language.subscribe(function() {
self.interpreter(undefined);
});
};
ko.applyBindings(new Thing());
my sample data:
roster = [
{ "language": "Spanish",
"interpreters": [
{"name" : "Paula"},
{"name" : "David"},
{"name" : "Humberto"},
{"name" : "Erika"},
{"name" : "Francisco"},
]
},
{"language":"Russian",
"interpreters":[{"name":"Yana"},{"name":"Boris"}]
},
{"language":"Foochow",
"interpreters":[{"name":"Lily"},{"name":"Patsy"}]
},
/* etc */
Now, I did figure out that I can hack around this and get the desired effect by putting
{ "language":"", "interpreters":[] }
at the front of my roster data structure, and that's what I guess I will do unless one of you cognoscenti can show me the more elegant way that I am overlooking.
After using both Knockout and Vuejs, I found Vuejs much easier to work with. Knockout is a bit out dated and no longer supported by any one or group.
Having said that, here is how I addressed your issue. The comments here refer to the link you provided not your code so I could build my own test case.
My working sample is at http://jsbin.com/gediwal/edit?js,console,output
I removed the optionsCaption from both select boxes.
Added the following item to the data (note that this has to be the first item in the arry):
{"products":{"name":"Waiting", "price":0}, "name":"Select..."},
I added the disable:isDisabled to the second selectbox cause I want it to be disabled when nothing is selected in the first selectbox.
added self.isDisabled = ko.observable(true); to the cartline model
altered the subscription to check the new value. If it is the select option the second one gets lock.
function formatCurrency(value) {
return "$" + value.toFixed(2);
}
var CartLine = function() {
var self = this;
// added this to enable/disable second select
self.isDisabled = ko.observable(true);
self.category = ko.observable();
self.product = ko.observable();
self.quantity = ko.observable(1);
self.subtotal = ko.computed(function() {
return self.product() ? self.product().price * parseInt("0" + self.quantity(), 10) : 0;
});
// Whenever the category changes, reset the product selection
// added the val argument. Its the new value whenever category lchanges.
self.category.subscribe(function(val) {
self.product(undefined);
// check to see if it should be disabled or not.
self.isDisabled("Select..." == val.name);
});
};
var Cart = function() {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
self.grandTotal = ko.computed(function() {
var total = 0;
$.each(self.lines(), function() { total += this.subtotal() })
return total;
});
// Operations
self.addLine = function() { self.lines.push(new CartLine()) };
self.removeLine = function(line) { self.lines.remove(line) };
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
productName: line.product().name,
quantity: line.quantity()
} : undefined
});
alert("Could now send this to server: " + JSON.stringify(dataToSave));
};
};
I experimenting something with mvc and knockout.js but maybe a have binding problem.
My viewmodel is:
var urlPath = window.location.pathname;
var currencyVm = function () {
var self = this;
var validationOptions = { insertMessages: true, decorateElement: true, errorElementClass: 'errorFill' };
ko.validation.init(validationOptions);
//ViewModel
self.ID = ko.observable(0);
self.Id_Region = ko.observable("");
self.Description = ko.observable("");
self.Symbol = ko.observable("");
self.PayPalCode = ko.observable("");
self.IFSCode = ko.observable("");
self.isGridVisible = ko.observable(true);
self.isEditVisible = ko.observable(false);
self.isAddVisible = ko.observable(false);
//Objects ---------------------------------------------
self.Currency = ko.observable();
self.Currencys = ko.observableArray([]);
//Methods ---------------------------------------------
//Edit
self.editCurrency = function (dataItem) {
self.isGridVisible(false);
self.isEditVisible(true);
self.ID = ko.observable(dataItem.ID);
self.Id_Region = ko.observable(dataItem.Id_Region);
self.Description = ko.observable(dataItem.Description);
self.Symbol = ko.observable(dataItem.Symbol);
self.PayPalCode = ko.observable(dataItem.PayPalCode);
self.IFSCode = ko.observable(dataItem.IFSCode);
//var vm = ko.mapping.fromJS(dataItem);
//self.Currency(vm);
};
//Add
self.addCurrency = function () {
self.isGridVisible(false);
self.isAddVisible(true);
self.isEditVisible(false);
self.reset();
}
// Cancel Edit
self.cancelEdit = function () {
self.isEditVisible(false);
self.isGridVisible(true);
}
// Cancel Add
self.cancelAdd = function () {
self.isAddVisible(false);
self.isGridVisible(true);
}
//Reset
self.reset = function () {
self.ID(0);
self.Id_Region("");
self.Description("");
self.Symbol("");
self.PayPalCode("");
self.IFSCode("");
}
//Actions --------------------------------------------------
var Currency = {
ID: self.ID,
Id_Region: self.Id_Region,
Description: self.Description,
Symbol: self.Symbol,
PayPalCode: self.PayPalCode,
IFSCode: self.IFSCode
};
//Create
self.createCurrency = function () {
$.ajax({
url: "/Currency/CreateCurrency",
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Currency),
success: function (data) {
self.isEditVisible(false);
self.isAddVisible(false);
self.isGridVisible(true);
$("#gridCurrencies").data("kendoGrid").dataSource.read();
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
});
}
// Update
self.updateCurrency = function () {
$.ajax({
url: "/Currency/UpdateCurrency",
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Currency),
success: function (data) {
self.isEditVisible(false);
self.isEditVisible(false);
self.isGridVisible(true);
$("#gridCurrencies").data("kendoGrid").dataSource.read();
}
})
}
//Delete
self.deleteCurrency = function (currency) {
$.confirm({
title: "Delete",
content: "Sure to delete ?",
confirm: function () {
$.ajax({
url: "/Currency/DeleteCurrency",
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(currency),
success: function (data) {
$("#gridCurrencies").data("kendoGrid").dataSource.read();
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
});
},
cancel: function () {
}
});
}
};
in the view I call applybinding and then based on selected row of the Telerik grid I call editCurrency or deleteCurrency.
<script>
var viewModel = null;
$(function () {
viewModel = new currencyVm();
ko.applyBindings(viewModel);
});
function deleteCurrency(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
viewModel.deleteCurrency(dataItem);
}
function editCurrency(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
viewModel.editCurrency(dataItem);
}
</script>
In the markup I have the html elements with the bindings:
Thi is the div for add:
<div class="panel panel-default" data-bind="visible: isAddVisible" style="display:none">
<div class="panel-heading">Add New Currency</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.IFSCode)
<input type="text" data-bind="value: $root.IFSCode, valueUpdate: 'keypress'" class="form-control " />
</div>
<div class="col-md-3">
#Html.LabelFor(model => model.PayPalCode)
<input type="text" data-bind="value: $root.PayPalCode, valueUpdate: 'keypress'" class="form-control " />
</div>
<div class="col-md-3">
#Html.LabelFor(model => model.Symbol)
<input type="text" data-bind="value: $root.Symbol, valueUpdate: 'keypress'" class="form-control " />
</div>
</div>
<div class="row">
<div class="col-md-9">
#Html.LabelFor(model => model.Description)
<input type="text" data-bind="value: $root.Description" class="form-control" />
</div>
</div>
<br />
<div class="row">
<div class="col-md-3">
<input data-bind="click: $root.createCurrency" type="button" class="btn btn-success btn-sm" value="#DbRes.T("Save", "Common")" />
<input data-bind="click: cancelAdd" type="button" class="btn btn-warning btn-sm" value="#DbRes.T("Cancel", "Common")" />
</div>
</div>
</div>
the edit div is like the add div but use different binding like data-bind="value: IFSCode"
The problem is that in add mode it work but when I edit I dont see nothing
in the textbox elements.
Also I use the to debug,
in add mode I can see the observables updating while I type something in textbox,
in edit mode the observables are emtpy and remain while typeing something.
May some body help please to understand what appen to this code
Your help is very appreciated.
Right now I am populating radio button from the observable array,
<div data-bind="foreach: cars">
<div>
<input type='radio' data-bind="checked: $root.vehicle, checkedValue: id, value:id"><span data-bind="text: model"></span>
</div>
</div>
Model data,
public class MyViewModel
{
public List<Cars> cars {get; set;}
}
public class Cars
{
public int Id{get; set;}
public string Make {get; set;}
public string Model {get; set;}
}
Say if I want to populated radio button for Make 'Honda' and dropdown list for make 'Toyota'. How to do that?
Basically, I am trying populate two different list of controls from same observable array.
If I understand what exactly you want to do, here is an example through what you could do :
Example :https://jsfiddle.net/kyr6w2x3/85/
HTML :
<div data-bind="foreach: Cars">
<input type='radio' data-bind="checked :$parent.VehicleSelected ,checkedValue: Make, value:Id">
<span data-bind="text: Make"></span>
<select data-bind="foreach:Models,visible:IsSelected" >
<option data-bind="text:Name , value:Id"></option>
</select>
<br />
</div>
JS:
var data = [
{Id:1,Make :"TOYOTA",Model: [{Id:1,Name:"COROLLA"},{Id:2,Name:"CAMERY"},{Id:3,Name:"PERADO"}]},
{Id:2,Make :"HONDA",Model:[{Id:4,Name:"CIVIC"},{Id:5,Name:"ACCORD"},{Id:6,Name:"PILOT"}]},
{Id:3,Make :"NISSAN",Model:[{Id:7,Name:"SENTRA"},{Id:8,Name:"ALTIMA"},{Id:9,Name:"JUKE"}]}];
function AppViewModel() {
var self = this ;
self.Cars = ko.observableArray($.map(data, function (item) {
return new CarItemViewModel(item);
}));
self.VehicleSelected = ko.observable();
self.VehicleSelected.subscribe(function(newValue){
ko.utils.arrayForEach(self.Cars(), function(item) {
if (item.Make().toUpperCase() === newValue.toUpperCase()) {
return item.IsSelected(true);
}else{
return item.IsSelected(false);
}
});
})
}
var CarItemViewModel = function (data){
var self = this ;
self.Id = ko.observable(data.Id);
self.Make = ko.observable(data.Make);
self.Models = ko.observableArray($.map(data.Model, function (item) {
return new ModelsItemViewModel(item);
}));
self.IsSelected = ko.observable(false);
}
var ModelsItemViewModel = function (data){
var self = this ;
self.Id = data.Id;
self.Name = data.Name;
}
var appVM = new AppViewModel()
ko.applyBindings(appVM);
My interpretation of your question:
You have one variable that holds all your data
You want to render multiple UI elements that represent sub-sets of these data
A good way to do this is by using ko.computeds that return the filtered result of an observableArray. An example:
var allCars = ko.observableArray([
{"name":"CIVIC","make":"HONDA"},
{"name":"SENTRA","make":"NISSAN"}];
var hondas = ko.computed(function() {
return allCars().filter(function(car) {
return car.make === "HONDA";
});
});
Because the computed uses the allCars observable, it is notified when the source data changes. The filter method is re-evaluated. In the snippet below you can see that you can push new data to your source and is automatically put in the right subset!
var allCars = ko.observableArray([
{"name":"CIVIC","make":"HONDA"},
{"name":"ACCORD","make":"HONDA"},
{"name":"PILOT","make":"HONDA"},
{"name":"SENTRA","make":"NISSAN"},
{"name":"ALTIMA","make":"NISSAN"},
{"name":"JUKE","make":"NISSAN"}]);
var hondas = ko.computed(function() {
return allCars().filter(function(car) {
return car.make === "HONDA";
});
});
var nissans = ko.computed(function() {
return allCars().filter(function(car) {
return car.make === "NISSAN";
});
});
var otherBrands = ko.computed(function() {
return allCars().filter(function(car) {
return car.make !== "NISSAN" &&
car.make !== "HONDA";
});
});
var inputVM = {
name: ko.observable(""),
make: ko.observable(""),
add: function() {
allCars.push({
name: this.name(),
make: this.make().toUpperCase()
});
}
};
ko.applyBindings({
hondas: hondas,
nissans: nissans,
allCars: allCars,
otherBrands: otherBrands,
inputVM: inputVM
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<h2>Honda</h2>
<ul data-bind="foreach: hondas">
<li data-bind="text: name"></li>
</ul>
<h2>Nissan</h2>
<ul data-bind="foreach: nissans">
<li data-bind="text: name"></li>
</ul>
<h2>Other brands</h2>
<ul data-bind="foreach: otherBrands">
<li data-bind="text: name"></li>
</ul>
<h2>Add car</h2>
<div data-bind="with: inputVM">
<label>
Name:
<input type="text" data-bind="value: name">
</label>
<label>
Make:
<input type="text" data-bind="value: make">
</label>
<button data-bind="click: add">Add</button>
</div>
Again next question , this time a tricky one,
Datasource:
var dsCountryList =
new kendo.data.DataSource({
transport: {
read: {
dataType: "jsonp",
url: "/Masters/GetCountries"
}
},
schema: {
model: {
id: "CountryID",
fields: {
"CountryDesc": {
}
}
}
}
});
Observable object
function Set_MVVMSupplier() {
vmSupplier = kendo.observable({
SupplierID: 0,
SupplierName: "",
AccountNo: "",
CountryList: dsCountryList,
});
kendo.bind($("#supplierForm"), vmSupplier);
}
here is the html which is bind to observable object , but i am not getting combobox filled, also each time i clicked the combo request goes to server and bring data in json format for countryID, CountryDesc
<div class="span6">
<div class="control-group">
<label class="control-label" for="txtCountryId">Country</label>
<div class="row-fluid controls">
#*<input class="input-large" type="text" id="txtCountryId" placeholder="CountryId" data-bind="value: CountryId">*#
<select id="txtCountryId" data-role="dropdownlist"
data-text-field="CountryDesc" data-value-field="CountryID" , data-skip="true"
data-bind="source: CountryList, value: CountryDesc">
</select>
</div>
</div>
</div>
I didn't get the answer , so i found an alternate working ice of code. just have a look and if it helps then please vote.
created model for ddl in js file
ddl = kendo.data.Model.define({
fields: {
CountryId: { type: "int" },
ConfigurationID: { type: "int" }
}
});
added var ddl to MVVM js file
vmSupplier = kendo.observable({
CountryId: new ddl({ CountryId: 0 }),
ConfigurationID: new ddl({ ConfigurationID: 0 }),});
added code in controller
using (CountriesManager objCountriesManager = new CountriesManager())
{
ViewBag.Countries = new SelectList(
objCountriesManager.GetCountries().Select(p => new { p.CountryID, p.CountryDesc })
, "CountryID", "CountryDesc"); ;
}
added code in cshtml
<div class="span4">
<label class="control-label" for="txtCountryId">Country</label>
#Html.DropDownList("Countries", null,
new System.Collections.Generic.Dictionary<string, object> {
{"id", "txtCountryId" },
{ "data-bind","value: CountryId"} })
</div>
this way i got solved the problem