I have below code to create Drop-down:
Below code for HTML to render Drop-down as:
<input class="form-control selectedTextBox mobile-space" list="rider" type="text" id="ridername" placeholder="FirstName LastName"
data-bind="trimedValue: item().Name, datalist: {
options: app.viewModel.riderProfiles(),
optionsValue: 'Id',
optionsText: 'Name',
value: app.viewModel.selectedRiderId
}" />
Below is Knockout.js handler:
ko.bindingHandlers.datalist = (function () {
function getVal(rawItem, prop) {
var item = ko.unwrap(rawItem);
return item && prop ? ko.unwrap(item[prop]) : item;
}
function findItem(options, prop, ref) {
return ko.utils.arrayFirst(options, function (item) {
return ref === getVal(item, prop);
});
}
return {
init: function (element, valueAccessor, allBindingsAccessor) {
var setup = valueAccessor(),
textProperty = ko.unwrap(setup.optionsText),
valueProperty = ko.unwrap(setup.optionsValue),
dataItems = ko.unwrap(setup.options),
myValue = setup.value,
koValue = allBindingsAccessor().value,
datalist = document.createElement("DATALIST");
// create an associated <datalist> element
datalist.id = element.getAttribute("list");
document.body.appendChild(datalist);
// when the value is changed, write to the associated myValue observable
function onNewValue(newVal) {
var dataItems = ko.unwrap(setup.options),
selectedItem = findItem(dataItems, textProperty, newVal),
newValue = selectedItem ? getVal(selectedItem, valueProperty) : void 0;
if (ko.isWriteableObservable(myValue)) {
myValue(newValue);
}
}
// listen for value changes
// - either via KO's value binding (preferred) or the change event
if (ko.isSubscribable(koValue)) {
koValue.subscribe(onNewValue);
} else {
ko.utils.registerEventHandler(element, "change", function () {
onNewValue(this.value);
});
}
// init the element's value
// - either via the myValue observable (preferred) or KO's value binding
if (ko.isObservable(myValue) && myValue()) {
element.value = getVal(findItem(dataItems, valueProperty, myValue()), textProperty);
} else if (ko.isObservable(koValue) && koValue()) {
onNewValue(koValue());
}
},
update: function (element, valueAccessor) {
var setup = valueAccessor(),
datalist = element.list,
dataItems = ko.unwrap(setup.options),
textProperty = ko.unwrap(setup.optionsText);
// rebuild list of options when an underlying observable changes
datalist.innerHTML = "";
ko.utils.arrayForEach(dataItems, function (item) {
var option = document.createElement("OPTION");
option.value = getVal(item, textProperty);
datalist.appendChild(option);
});
ko.utils.triggerEvent(element, "change");
}
};})();
And with only MAC(OS) & Safari (Web-Browser) below error message is shown as:
Message: Unable to process binding "datalist: function () {return { options:app.viewModel.riderProfiles(),optionsValue:'Id',optionsText:'Name',value:app.viewModel.selectedRiderId} }"
Message: undefined is not an object (evaluating 'u.innerHTML=""')
The HTML element contains a set of elements that represent the values available for other controls.
But "Safari" browser does not support it.
Related
I try to learn SAPUI5 with Samples frpm Demo kit Input - Checked. I get an error message: oInput.getBinding is not a function
I have a simple input field xml:
<Label text="Name" required="false" width="60%" visible="true"/>
<Input id="nameInput" type="Text" enabled="true" visible="true" valueHelpOnly="false" required="true" width="60%" valueStateText="Name must not be empty." maxLength="0" value="{previewModel>/name}" change= "onChange"/>
and my controller:
_validateInput: function(oInput) {
var oView = this.getView().byId("nameInput");
oView.setModel(this.getView().getModel("previewModel"));
var oBinding = oInput.getBinding("value");
var sValueState = "None";
var bValidationError = false;
try {
oBinding.getType().validateValue(oInput.getValue());
} catch (oException) {
sValueState = "Error";
bValidationError = true;
}
oInput.setValueState(sValueState);
return bValidationError;
},
/**
* Event handler for the continue button
*/
onContinue : function () {
// collect input controls
var that = this;
var oView = this.getView();
var aInputs =oView.byId("nameInput");
var bValidationError = false;
// check that inputs are not empty
// this does not happen during data binding as this is only triggered by changes
jQuery.each(aInputs, function (i, oInput) {
bValidationError = that._validateInput(oInput) || bValidationError;
});
// output result
if (!bValidationError) {
MessageToast.show("The input is validated. You could now continue to the next screen");
} else {
MessageBox.alert("A validation error has occured. Complete your input first");
}
},
// onChange update valueState of input
onChange: function(oEvent) {
var oInput = oEvent.getSource();
this._validateInput(oInput);
},
Can someone explain to me how I can set the Model?
Your model is fine and correctly binded.
The problem in your code is here, in the onContinue function
jQuery.each(aInputs, function (i, oInput) {
bValidationError = that._validateInput(oInput) || bValidationError;
});
aInput is not an array, so your code is not iterating on an array element.
To quickly fix this, you can put parentheses around the declaration like this:
var aInputs = [
oView.byId("nameInput")
];
Also, you could remove the first two lines of the _validateInput method since they are useless...
Usually, we set the model once the view is loaded, not when the value is changed. For example, if you would like to set a JSONModel with the name "previewModel", you can do as mentioned below.
Note that onInit is called when the controller is initialized. If you bind the model properly as follows, then the oEvent.getSource().getBinding("value") will return the expected value.
onInit: function(){
var oView = this.getView().byId("nameInput");
oView.setModel(new sap.ui.model.json.JSONModel({
name : "HELLO"
}), "previewModel");
},
onChange: function(oEvent) {
var oInput = oEvent.getSource();
this._validateInput(oInput);
},
...
Also, for validating the input text, you can do the following:
_validateInput: function(oInput) {
var oBinding = oInput.getBinding("value");
var sValueState = "None";
var sValueStateText = "";
var bValidationError = false;
if(oBinding.getValue().length === 0){
sValueState = "Error";
sValueStateText = "Custom Error"
}
oInput.setValueState(sValueState);
if(sValueState === "Error"){
oInput.setValueStateText(sValueStateText);
}
return bValidationError;
},
Please note that the code above is not high quality and production ready as it's a quick response to this post :)
I am trying to create a custom binding handler to apply a role based access to fields on page.
In custom handler it will check values of other observables from viewModel and based on condition it will enable or disable input control.
But I am not able to get current ViewModel through bindingContext.$parent , $root, $data or $rawData.
when I debug on IE it only displays {...}
The issue occurs only on IE, It works fine on google crome.
Can someone help me on how do I get current ViewModel through bindingContext.
var divForm = document.getElementById('divform');
function AuditFormViewModel() {
self = this;
self.Name = ko.observable("Kiran");
self.Email = ko.observable("kiranparab0#gmail.com");
self.Complete = ko.observable(true);
self.Send = ko.observable(false);
self.conditionArray = [
{ Field: "Name", condition: [{ Property: "Complete", Value: true }, { Property: "Send", Value: true }] },
{ Field: "Email", condition: [{ Property: "Complete", Value: false }] }
];
}
ko.bindingHandlers.hasAccess = {
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var field = valueAccessor();
var accessConditions = [];
accessConditions = bindingContext.$data.conditionArray;
var condition = accessConditions.filter(function (cnd) {
return cnd.Field === field
})[0].condition;
var value = true;
for (var i = 0; i < condition.length; i++) {
var cndProp = condition[i].Property;
var cndVal = bindingContext.$data[cndProp]();
value = value && (condition[i].Value === cndVal);
}
ko.bindingHandlers.enable.update(element, function () { return value });
}
};
auditFormViewModel = new AuditFormViewModel();
ko.applyBindings(auditFormViewModel, divForm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<div id="divform">
Name : <input type="text" data-bind="value:Name, hasAccess:'Name'" />
<br />
Email : <input type="text" data-bind="value:Email, hasAccess:'Email'" />
</div>
Here is the fiddle
In my code I have not declared self as var,
its just change of line. 'var self = this' instead 'self = this'
I am having a problem with the dynamic creation of a Form. I have a directive that gets set against a form element. It uses Jquery to get the element by id. However it seems that it has not yet been added to the DOM.
<form class="form-horizontal">
<div class="control-group" ng-repeat="field in viewModel.fields">
<label class="control-label">{{field.label}}</label>
<div class="controls" ng-switch="field.type">
<input ng-switch-when="text" type="text" id="{{field.label}}" ng-model="field.data" validator="viewModel.validator" ruleSetName="personFirstNameRules"/>
<span ng-switch-when="text" validation-Message-For="{{field.label}}"></span>
</div>
</div>
<button ng-click="testID()">Submit</button>
</form>
If I hard code the ID attribute for the text field and on the span element validation-Message-For then their is no issue.The area where i am getting undefined is
var errorElementController = angular.element(errorElement).controller('ngModel');
var validatorsController = angular.element(errorElement).controller('validator');
The full directive is here
(function (angular, $) {
angular.module('directivesModule')
.directive('validationMessageFor', [function () {
return {
link: function (scope, element, attributes) {
var errorElementId = attributes.validationMessageFor;
if (!errorElementId) {
return;
}
var areCustomErrorsWatched = false;
var watchRuleChange = function (validationInfo, rule) {
scope.$watch(function () {
return validationInfo.validator.ruleSetHasErrors(validationInfo.ruleSetName, rule.errorCode);
}, showErrorInfoIfNeeded);
};
var watchCustomErrors = function (validationInfo) {
if (!areCustomErrorsWatched && validationInfo && validationInfo.validator) {
areCustomErrorsWatched = true;
var validator = validationInfo.validator;
var rules = validator.validationRules[validationInfo.ruleSetName];
for (var i = 0; i < rules.length; i++) {
watchRuleChange(validationInfo, rules[i]);
}
}
};
//alert(errorElementId);
// get element for which we are showing error information by id
var errorElement = $("#" + errorElementId);
console.log(angular.element(errorElement));
var errorElementController = angular.element(errorElement).controller('ngModel');
var validatorsController = angular.element(errorElement).controller('validator');
console.log(errorElementController);
console.log(validatorsController);
var getValidationInfo = function () {
return validatorsController && validatorsController.validationInfoIsDefined() ? validatorsController.validationInfo : null;
};
var validationChanged = false;
var subscribeToValidationChanged = function () {
if (validatorsController.validationInfoIsDefined()) {
validatorsController.validationInfo.validator.watchValidationChanged(function () {
validationChanged = true;
showErrorInfoIfNeeded();
});
// setup a watch on rule errors if it's not already set
watchCustomErrors(validatorsController.validationInfo);
}
};
var getErrorMessage = function (value) {
var validationInfo = getValidationInfo();
if (!validationInfo) {
return '';
}
var errorMessage = "";
var errors = validationInfo.validator.errors[validationInfo.ruleSetName];
var rules = validationInfo.validator.validationRules[validationInfo.ruleSetName];
for (var errorCode in errors) {
if (errors[errorCode]) {
var errorCodeRule = _.findWhere(rules, { errorCode: errorCode });
if (errorCodeRule) {
errorMessage += errorCodeRule.validate(value).errorMessage;
break;
}
}
}
return errorMessage;
};
var showErrorInfoIfNeeded = function () {
var validationInfo = getValidationInfo();
if (!validationInfo) {
return;
}
var needsAttention = validatorsController.ruleSetHasErrors() && (errorElementController && errorElementController.$dirty || validationChanged);
if (needsAttention) {
// compose and show error message
var errorMessage = getErrorMessage(element.val());
// set and show error message
element.text(errorMessage);
element.show();
} else {
element.hide();
}
};
subscribeToValidationChanged();
if (errorElementController)
{
scope.$watch(function () { return errorElementController.$dirty; }, showErrorInfoIfNeeded);
}
scope.$watch(function () { return validatorsController.validationInfoIsDefined(); }, subscribeToValidationChanged());
}
};
}]);})
(angular, $);
The error on the console is
TypeError: Cannot read property 'validationInfoIsDefined' of undefined
at subscribeToValidationChanged (http://localhost/trax/app/Directives/validationMessage.js:50:52)
at link (http://localhost/trax/app/Directives/validationMessage.js:103:24)
at nodeLinkFn (https://code.angularjs.org/1.2.13/angular.js:6271:13)
at compositeLinkFn (https://code.angularjs.org/1.2.13/angular.js:5682:15)
at publicLinkFn (https://code.angularjs.org/1.2.13/angular.js:5587:30)
at boundTranscludeFn (https://code.angularjs.org/1.2.13/angular.js:5701:21)
at Object.controllersBoundTransclude [as transclude] (https://code.angularjs.org/1.2.13/angular.js:6292:18)
at https://code.angularjs.org/1.2.13/angular.js:20073:32
at Array.forEach (native)
at forEach (https://code.angularjs.org/1.2.13/angular.js:304:11) <span ng-switch-when="text" validation-message-for="{{field.label}}" class="ng-scope">
you are writing Directive name as camel case when you are define. in this case angular read this directive as - based values
so validation-Message-For should be validation-message-for in your Html code
<span ng-switch-when="text" validation-message-for="{{field.label}}"></span>
and change the input id attribute value assigning type:
remove the {{}} from id attribute
<input ng-switch-when="text" type="text" id="field.label" ng-model="field.data" validator="viewModel.validator" ruleSetName="personFirstNameRules"/>
update
problem with ng-switch when. in your Plunker the input tags are not rendering as input field.
Be aware that the attribute values to match against cannot be expressions.
They are interpreted as literal string values to match against. For example,
ng-switch-when="someVal" will match against the string "someVal" not against the
value of the expression $scope.someVal.
refer this Question. StackOverflow Question
Updated Plunker
I'm trying to write a jQuery code that works in this way:
When the page is loaded, it is presents only one field.
Selecting an option from that field, a new field is opened and the option have to be all the option of the first , except the option selected. And so on, also for the other created.
The jsfiddle is shown here
var globalObj = {};
var selectedObj = {};
var unselectedObj = {};
var currentSelection = "";
function deleteByVal(obj,val) {
for (var key in obj) {
if (obj[key] == val) delete obj[key];
}
}
$(document).ready(function () {
$(document).on('click', 'target', function(){
var curSelected = $(this).find(":selected").text();
});
$("#select1").one('click',function(){
$(this).children().each(function () {
globalObj[this.value] = this.innerHTML;
});
unselectedObj = globalObj;
});
$(document).on('change', '.prova > .target', function () {
$('div').removeClass('prova');
var $mySelect = $('<select>', {
class: 'target'
});
var selectedValue = $(this).find(":selected").text();
var found = 0;
$.each(selectedObj, function (val, text) {
if (val === selectedValue) {
found++;
}
});
if (found===0) {
selectedObj[this.value] = selectedValue;
deleteByVal(unselectedObj,selectedValue);
}
console.log(selectedValue);
console.log(selectedObj);
console.log(unselectedObj);
var obj = {}; //create an object
$(this).children().each(function () {
if (this.innerHTML!=selectedValue) {
//code
obj[this.value] = this.innerHTML;
}
});
console.log("Questo rappresenta obj:");
console.log(obj);
console.log("stampa obj conclusa");
$( "select" ).not(this).each(function( index ) {
var temp = {}; //create an object
$(this).children().each(function () {
if (this.innerHTML === selectedValue) {
console.log("eliminazione");
$(this).remove();
}
});
$this = $(this);
console.log("stampa temp");
console.log(temp);
console.log("fine stampa temp");
});
$.each(unselectedObj, function (val, text) {
$mySelect.append($('<option />', {
value: val,
text: text
}));
});
var $input = $('<input>', {
type: 'number',
style: 'width: 35px',
min: '1',
max: '99',
value: '1'
});
var $button = $('<button>', {
type: 'button',
class: 'remove_item',
text: 'delete'
});
$(this).parent().after($('<br>', {
class: 'acapo'
}), $('<div>', {
class: 'prova'
}).append($mySelect, $input, $button));
$(this).unbind('change');
$(this).unbind('click');
$(this).on('click', function(){
currentSelection = $(this).find(":selected").text();
});
$(this).on('change',function(){
console.log("nuovo bind");
var selectedValue = $(this).find(":selected").text();
if (currentSelection !== selectedValue) {
console.log(currentSelection + " to "+ selectedValue);
$( "select" ).not(this).each(function( index ) {
$(this).append($('<option />', {
value: currentSelection,
text: currentSelection
}));
$(this).children().each(function () {
if (this.innerHTML === selectedValue) {
console.log("eliminazione");
$(this).remove();
}
});
});
}
});
});
});
The code has some problems and I was thinking to use an existing plugin instead of that code. Is there anyone that knows a plug-in which makes that work?
Here's an option using javascript templating. I'm declaring my available options at the top in an array, thus separating my data model from the UI. I'm using the handlebars library to then compile a template and append it into the DOM. Fiddle: http://jsfiddle.net/LNP8d/1/
HTML/Handlebars
<script id="select-template" type="text/x-handlebars-template">
<div>
<select class="target" id ="select-{{id}}">
<option value="">Select an option…</option>
{{#each options}}
{{#unless selected}}
<option data-option-key="{{#key}}" value="{{value}}">{{label}}</option>
{{/unless}}
{{/each}}
</select>
<input type="number" style="width: 35px" min="1" max="99" value="1">
</div>
</script>
<div id="container">
</div>
Javascript
//Declare the available options
var options = {
option1: {
value: 1,
label: "Option 1"
},
option2: {
value: 2,
label: "Option 2"
},
option3: {
value: 3,
label: "Option 3"
},
option4: {
value: 4,
label: "Option 4"
},
}
source = $("#select-template").html(),
template = Handlebars.compile(source),
onScreen = 0;
//Adds another select menu
var showSelect = function(){
onScreen++;
$("#container").append(template({id:onScreen, options:options}))
};
//Listens to change events
$("body").on("change", ".target", function(){
options[$(this).find(":selected").data("option-key")].selected = true;
showSelect();
});
//Initialises the UI
showSelect();
Please note: this is not a complete example. If you decide to use this method, you'll need to add some checks for what happens when the options run out and if someone changes an option. I hope it's successful in showing you an alternative a potentially more flexible method though.
I think you are looking for something like this:
http://codeassembly.com/Simple-chained-combobox-plugin-for-jQuery/
I get metadata as string like "{Input:{'A':'System.Int32','B':'System.Int32'}, Output:System.Int32}"
I am using knockout.js and could use json.parse also. But are there any easy way to generate a inputform that let the user submit data for properties of input. (would it be better to change the metadata to be a list of properties?
I used this to generate the array of properties.
self.input = ko.observableArray([]);
if (data.MetaData) {
// alert(data.MetaData);
var d = JSON.parse(data.MetaData).Input;
for (var prop in d) {
self.input.push({name:ko.observable(prop),type:d[prop],value:ko.observable('')});
}
}
and View:
<ul data-bind="foreach:test().input">
<li >
<label data-bind="text:name, uniqueFor: name"></label>
<input placeholder="value" data-bind="value:value, uniqueId: name"/>
</li>
</ul>
and bindings:
ko.bindingHandlers.uniqueId = {
init: function (element, valueAccessor) {
var value = valueAccessor();
value.id = value.id || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);
element.id = value.id;
},
counter: 0,
prefix: "unique"
};
ko.bindingHandlers.uniqueFor = {
init: function (element, valueAccessor) {
var value = valueAccessor();
value.id = value.id || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);
element.setAttribute("for", value.id);
}
};