knockout js selected option - javascript

I have a select tag in my html with knockout js binding.
<select class="form-control " data-bind="options: loanTimesBorrower,
optionsText: loanTimesBorrower(),
value: loanTimeBorrower,
selectedOptions: loanTimesBorrowerini,
optionsCaption: 'Choose dates'">
</select>
Instead of choose date I want to show the default value as 180, since I have a array which stores this loantime as 180 days, 360 days etc.
this is the array
self.loanTimesBorrower = ko.observableArray();
self.loanTimesBorrowerini = ko.observableArray(self.loanTimesBorrower()[0]);
and I get this array populated by a foreach loop which is getting the loantimes from db like this.
$.each(items.investTimes, function (index, item) {
self.loanTimesBorrower.push(item.Loantime);
});
So I am not sure how the default value can be put as 180 instead of choose dates

Remove
optionsCaption: 'Choose dates'
It would default to the option you provided.

You can use it like this:
<select id="selectDate" class="form-control " data-bind="options: loanTimesBorrower,
optionsText: loanTimesBorrower(),
value: loanTimeBorrower,
selectedOptions: loanTimeBorrower[0],
optionsAfterRender: $root.setDefaultDate">
</select>
And in your javascript you can do something like:
self.setDefaultDate= function (option, object) {
if (typeof object !== "undefined" && object !== null) {
if(object.value === 180) {
$("#selectDate").find(option).prop('selected', true);
}
}
};
if you show me what the object in your array looks like I can edit the answer for a better fit. But that should help you to find your way

Related

Javascript search for dropdown inside knockout data-bind foreach

Using knockout js
I have setup my dropdown inside a table as:
<tbody data-bind="foreach: items">
<tr>
<td id="tdName"><select class="form-control" data-bind="options: $parent.ddl, optionsText: 'firstName', value: selectedValue, optionsCaption: '--Select--', attr: { name: 'Items[' + $index() + '].Name', id: 'Items[' + $index() + '].Name'}"> </select></td>
</tr>
So it creates multiple rows of dropdowns. The above in html looks as below:
<select class="form-control" data-bind="options: $parent.ddl, optionsText: 'firstName', value: selectedValue, optionsCaption: '--Select--', attr: { name: 'Items[' + $index() + '].Name', id: 'Items[' + $index() + '].Name'}" name="Items[0].Name" id="Items[0].Name"><option value="">--Select--</option><option value="">Alex</option><option value="">Sam</option> </select>
I have a save button where I want to validate if this dropdown was selected on or not.
So I am trying to use the below code on save button click:
var selectList = $('#tdName > select');
for (var ddl of selectList ) {
if (ddl.value == '') {
ddl.className = "required text-danger form-control ddl-error"; }
}
In my console when I debug I can see the selectList as: select#Items[0].Name.form-control
So basically what I am trying to do above is loop through all the ddl and if no selection is made add the error class to it so that it is highlighted.
The issue is ddl.value is always '' so the dropdown is always highlighted.
Not sure here if I am looping though correctly here
I have my jsfiddle here as:
https://jsfiddle.net/aman1981/7wqvr854/51/
To see in action click add row, get data to populate the dropdown.
Would appreciate inputs.
You shouldn't access the DOM to check for selected values. You're already binding them to your viewmodel!
The validity check inside the Save method can access items directly:
self.save = function() {
var rows = self.items();
if (!rows.length)
alert("You cannot save an empty table");
else if (!rows.every(r => r.selectedSeperator())
alert("Some rows do not have a selected seperator");
// etc.
};

Set "title" of selected value from dropdown after selection using knockout

I am using knockout js with ASP.NET MVC. I want to show the selected value's text on title when user hover on the selected value after selecting on the dropdown. So if bigger value hidden goes can show in title.
like: if I have three values One, Two , BiggerValuethathidden.
So now obviously if my dropdown size is not that much bigger like third value, my third value will go hidden after size defined for dropdownlist.So I want to show when set value as title on hover.
Now I have try to implement the dropdownlist bind like this:
<select class="form-control" data-bind="options: Accounts, optionsCaption: ' -- ', optionsText: function (item) { return item.AccountName }, optionsValue: function (item) { return item.Id }, value:AccountId, click: setTitle" required="required" data-parsley-required-message="Account is required" id="ddlAccounts">
To Set after so many searches , I am trying to do it like this:
<div title="" id=dvAccount">
<select class="form-control" data-bind="options: Accounts, optionsCaption: ' -- ', optionsText: function (item) { return item.AccountName }, optionsValue: function (item) { return item.Id }, value:AccountId, click: setTitle" required="required" data-parsley-required-message="Account is required" id="ddlAccounts">
</div>
click event function based on Solution:
setTip = function(c, event){
var element = event.currentTarget;
var qref = element.getAttribute('Qref');
var click_id = element.id;
return true;
}
Where am I going wrong?
Please some one help me to do this tricky trick!
You can use "attr" binding ("attr: { title: AccountId }" - you can put another (human-readable) value instead of AccountId):
<div data-bind="attr: { title: AccountId }" id=dvAccount">
<select class="form-control" data-bind="options: Accounts, optionsCaption: ' -- ', optionsText: function (item) { return item.AccountName }, optionsValue: function (item) { return item.Id }, value:AccountId, click: setTitle" required="required" data-parsley-required-message="Account is required" id="ddlAccounts">
</div>
Uffffff it is accidently or I don't know but from last 3 questions I asked question and me myself post my answer, this time again.
I found an extreme helpful solution for title of dropdown selected value:
Just use this jquery and css combination:
$('select').each(function(){
var tooltip = $(this).tooltip({
selector: 'data-toggle="tooltip"',
trigger: 'manual'
});
var selection = $(this).find('option:selected').text();
tooltip.attr('title', selection)
$('select').change(function() {
var selection = $(this).find('option:selected').text();
tooltip.attr('title', selection)
});
});
Thanks to TSV for such faster response and help me but this one is better as per my application.

Assign value to Knockout observable?

I have a page that populates its fields(dropdowns and textboxes) from the DB when the page loads via VIEWDATA object from controller.
I am using KnockoutJS for data-binding, below is the scenario
HTML & JS(dropdown)
#if (Filter!= null)
{
<select data-bind="options: RsnAdmAct,
value: selectedRsnAdmAct,
optionsCaption:'Choose...',
optionsValue:'RsnAdminActionID',
optionsText:'RsnAdminActionDescp',
optionsAfterRender: function()
{
setOptionRSN(#Filter.RsnForAdminAction);
}">
</select>
}
self.RsnAdmAct = ko.observableArray([]);
self.selectedRsnAdmAct = ko.observable();
$.getJSON("GetRAA", null, function (data) {
self.RsnAdmAct(data);
});
self.selectedRsnAdmAct = ko.observable();
self.setOptionRSN = function (x) {//reason for admin action dd
self.selectedRsnAdmAct(x);
};
this does update the drop-down with the assigned value "X".
But the same does not assign value for the text-boxes as below
HTML & JS(textbox)
#if (#Filter != null)
{
<input placeholder="Downstream"
data-bind="value: DownStream,
optionsAfterRender:function()
{
setOptionDstream(#Filter.DownstreamNumber);
}">
}
self.DownStream = ko.observable();
self.setOptionDstream = function (x) {//down stream number
self.DownStream(x);
};
optionsAfterRender applies to options; a text input has no options. Setting the value of DownStream will set the value of the text box, because that's how the value binding works.
I tried to search for a proper way to do this but below is the way it works and no other alternative worked.I had to move the function which assigns the value to the texbox observable into the options after render attribute of the drop down as below
#if (Filter!= null)
{
<select data-bind="options: RsnAdmAct,
value: selectedRsnAdmAct,
optionsCaption:'Choose...',
optionsValue:'RsnAdminActionID',
optionsText:'RsnAdminActionDescp',
optionsAfterRender: function()
{
setOptionRSN(#Filter.RsnForAdminAction);
setOptionDstream(#Filter.DownstreamNumber);
}">
</select>
}
This is the only way it worked for me.Thank you for the posts and comments

Selected Dropdownlist vaue is not updating in the UI Knockout js

In my application, I am using a drop down list as shown below.
<select id="ddlcurrency" data-bind="options: $root.ddlOppCurrency, optionsText: 'CurrencyCode', optionsValue: 'CurrencyCode', optionsCaption: 'Select..', value: selectedCurrId, valueUpdate: 'change'" class="form-control"></select>
I am having a div in which the selected dropdown value has to be binded.
<div class="col-md-8 value" data-bind="text: (CurrencyID() == '' || CurrencyID() == null || CurrencyID() == undefined) ? '--' : CurrencyID">
I have created a function to bind dropdown list and a function to bind the selected value as shown below.
function ddlOppCurrency(CurrencyCode)
{
this.CurrencyCode = ko.observable(CurrencyCode);
}
function Config(CurrencyID)
{
this.selectedCurrId = ko.observable(CurrencyID);
}
Now, when I change the dropdown list, the selected value is not updating in UI. Can anyone let me know how to achieve this.
Thanks in advance.

dropdown knockoutjs with value from server

I am working on a drop down menu within a TR .. I have true, false or none as the value that I receive from server and I want that to change the drop down option as in example below.
The first one is working but I want the second one to function as the first one
Example is here: http://jsfiddle.net/3xLgJ/
This is my HTML:
<div data-bind='text: incomingValue'></div>
<select data-bind="value: incomingValue">
<option value="true">Yes</option>
<option value="false">No</option>
<option value="none">Don't Know</option>
</select>
How can I implment this as above as this is within a tr and to function as above
<select data-bind='options: yesno, value: incomingValue'/>
Here is my knockout
var myModelView = function () {
self = this;
self.yesno = ko.observableArray(['Yes', 'No', 'Don\'t know']);
self.incomingValue = ko.observable('none');
};
var moView = new myModelView();
ko.applyBindings(moView);
Thanks
Thanks
The best solution is probably to slightly reconstruct the view model to use objects instead of simple strings:
// Create a "class" that represents an option
var Option = function(id, caption) {
this.id = id;
this.caption = caption;
};
Now you populate the observable array with objects constructed from this function:
self.yesno = ko.observableArray([
new Option('true', 'Yes'),
new Option('false', 'No'),
new Option('none', 'Don\'t know')
]);
You can use the "optionsText" binding to correctly bind these objects to the markup:
<select data-bind="options: yesno,
optionsText: 'caption',
value: selectedItem"></select>
If you receive a string "none" from the server, you need to find the object representing this option:
var incomingValue = 'none';
// Find the first object that is a match in the observable array "yesno"
var incomingItem = ko.utils.arrayFirst(self.yesno(), function(item) {
return item.id == incomingValue;
});
self.selectedItem = ko.observable(incomingItem);
When displaying the selection somewhere else you'll need to consider that the selection is represented by an object:
<div data-bind='text: selectedItem().caption'></div>
Demo: http://jsfiddle.net/3xLgJ/2/
You need to use the optionsText and optionsValue bindings. You'll need to make an observable array of values and text:
self.yesno = ko.observableArray([
{value:"true",text:"Yes"},
{value:"false",text:"No"},
{value:"none",text:"Don't Know"}]);
then, you need to do something like this in your html:
<select data-bind="options: yesno2, optionsText: 'text',optionsValue: 'value', value: incomingValue"></select>
See here for a working example

Categories

Resources