I have a java / Spring MVC application that includes forms that interface with tables. On one of the pages, I have designed it so that when a row is clicked on the table, form data is populated using the data that is in that row.
Javascript code:
$('#table tbody').on('click', 'tr', function () {
var idx = table.row(this).index();
var vName = document.getElementById("userName");
vName.value = table.cell(idx, 7).data();
This works well for the text form fields. Where I am running into a problem is in the "userName" field, since that is a list (form:select) field.
I'm not really sure how I would go about the process of having my app be able to locate the list index of a name in the dropdown list based on the text data that it is reading from the table.
Here is the html for the dropdown field:
<spring:bind path="model.userName">
<label for="fullName">Select User:</label>
<form:select cssClass="form-control" path="model.userName" id="userName" name="userName">
<form:option value=""></form:option>
<form:options items="${userList}" itemLabel="fullName" itemValue="ID"/>
</form:select>
</spring:bind>
The dropdown list, ${userList}, is created by building a List in my DAO, along with the following RowMapper method:
private static class UserRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int i) throws SQLException {
return new Users(rs.getLong("ID"),
rs.getString("LNAME") + ", " + rs.getString("FNAME"));
}
}
When you set a value of a select element, in fact you are setting the option with this value as selected, while here you are using the name so you are dealing with the content of the option and not it's value.
So in your example when you have the selected userName from your table you just need to loop through the select options and set the appropriate option as selected.
This is the code you need:
$('#table tbody').on('click', 'tr', function() {
var idx = table.row(this).index();
var vName = document.getElementById("userName");
for (i in vName.options) {
//I test on the innerText here because FF doesn't support it
var optionText = typeof vName.options[i].innerText !== 'undefined' ? vName.options[i].innerText : vName.options[i].textContent;
if (optionText === table.cell(idx, 7).data()) {
vName.selectedIndex = i;
break;
}
}
});
This is a brief Snippet Example:
$('#name').on('change', function() {
var vName = document.getElementById("userName");
for (i in vName.options) {
var optionText = typeof vName.options[i].innerText !== 'undefined' ? vName.options[i].innerText : vName.options[i].textContent;
if (optionText === $(this).val()) {
vName.selectedIndex = i;
break;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter name:
<input type="text" id="name" />
<select name="userName" id="userName">
<option value="">Muhammad</option>
<option value="">Alain</option>
<option value="">John</option>
<option value="">Ali</option>
<option value="">Maria</option>
<option value="">Lee</option>
<option value="">Alessandro</option>
</select>
Usually the best way to get data from a server to the front end is as a JSON string/object then we can easily manipulate that just like you're doing already.
I think you're pretty much there you're just missing one part.
In this below example i'm listing the same users in a table and menu and on click of the table row the selected user in the drop down is defaulted.
For example with this sample table data.
JS:
var users = [{
ID: 0,
LNAME: "First",
FNAME: "Senior"
}, {
ID: 1,
LNAME: "Second",
FNAME: "Sir"
}, {
ID: 2,
LNAME: "Third",
FNAME: "Chap"
}, {
ID: 3,
LNAME: "Fourth",
FNAME: "Mr"
}];
mag.module('userName', {
view: function(state) {
state.tr = state.option = users.map(function(user) {
return {
_selected: user.ID == state.index ? true : null,
_text: user.FNAME + ' ' + user.LNAME,
_value: user.ID
}
});
state.$tr = {
_onclick: function(e, i) {
state.index = i;
state.span = users[i].FNAME + users[i].LNAME
}
}
}
});
HTML:
<div id="userName">
<table>
<tr></tr>
</table>
<hr/>
<label for="fullName">Select User: <span></span></label>
<select class="form-control" name="userName">
<option></option>
</select>
</div>
Here is the full working example: http://jsbin.com/bokiqebezo/1/edit?html,js,output
Hope this helps!
Related
Using easyAutocomplete plugin, I autocomplete an input field and take the selected value and display them on a dropdown .
What I want to do, is have a hidden field that would have the id of the value.
My JSON File returns something like this :
{ "name": "Emily"
"id" : 1
"jobData": [
{
"id":1
"loc":"AL"
},
{
"id":2
"loc":"BG"
}
]
Once I select Emily from my users, my dropdown gets filled with Locations of her job.
How do I also save the Id of the location in a hidden field so that I can send it to my controller?
This is my JS function:
function AutoCompleteS() {
$("#basics").keyup(function(e) {
this.query = e.target.value;
var options = {
url: function(query) {
return "/getUser/"+ query
},
getValue:"name"
list: {
onClickEvent: function() {
var value = $("#basics").getSelectedItemData();
function toArray(value){
return value.loc;
}
var allLocations=value.jobData.map(toArray);
$.each(allLocations,function(i,p){
$('#select').append($('<option></option>').val(p).html(p));
})
}
}
};
$('#basics').easyAutocomplete(options);
});
}
How do I get and pass the id ?
EDIT:
html code:
<label for="client1" class=" control-label">First Client</label> <input type="text" name="client" value="" class="form-control input-lg " id="basics"/>
<label for="sel1">Select location:</label>
<select class="form-control input-lg" id="select" >
<option></option>
<input type="text" class="hidden" />
</select>
easyAutocomplete issues:
Your code should be more like this (see remote data source example) - i.e. you should only call easyAutocomplete once:
$("#basics").easyAutocomplete({
url: function(query) {
return "/getUser/" + query;
},
getValue: "name",
list: {
// ...
}
});
HTML issues:
Move the input outside the select, and give them both names (so the values can be submitted to server):
<select class="form-control input-lg" id="select" name="location">
<option></option>
</select>
<input type="text" class="hidden" name="job-id" id="job-id">
To set the value of the hidden field when the select value changes, you need a change handler:
function updateSelect(jobData) {
// Reset options:
$("#select")
.empty()
.append(new Option());
// Add locations:
jobData.forEach(function(job) {
$("#select").append(new Option(job.loc));
});
// Handle dropdown change:
$("#select")
.off("change")
.on("change", function() {
// Reset job id (needed when user selects blank option at top of dropdown)
$("#job-id").val("");
var selectedLocation = this.value;
jobData.forEach(function(job) {
if (job.loc === selectedLocation) {
// Copy job id to hidden field:
$("#job-id").val(job.id);
}
});
});
}
Call updateSelect from your easyAutocomplete onClickEvent handler:
onClickEvent: function() {
var value = $("#basics").getSelectedItemData();
updateSelect(value.jobData);
}
My Html.
I have auto-complete search bar(text box) along with 3 different option to filter search that is based on 1)Employee name 2) Employee ID 3) Email ID.
So based on the filter option selected data source(i mean list) should change.
Help me to change the data source in the script based on the option selected in dropdown
<div class="col-sm-3" style="margin:15px 0px 0px 20px; cursor:pointer; width:180px!important">
<select class="form-control" id="searchFilterList" style="width:200px!important" onchange="changeSearchBarID()">
<option value="employeeName">Employee Name</option>
<option value="employeeID">Employee ID</option>
<option value="emailID">Email ID</option>
</select>
<input class="form-control" type="text" placeholder="Search..." id="EmployeeNameSearch"; style="max-width:800px!important;">
My Script. I have three list
<script>
$(function () {
var employeeNameList = [
"Abishek Chandrasekar", "Bharat", "Deepak", "Eric",
"Fizil", "Gowtham", "Harbajan",
"Akshara", "Roshini"
];
var employeeIDList = [
"SF1010", "SF2010", "SF3010", "SF4010",
"SF5010", "SF6010", "SF7010",
"SF9010", "SF8010"
];
var emaiIDList = [
"abishek.chandrasekar#syncfusion.com", "bharath#syncfusion.com", "deepak#syncfusion.com", "eric#syncfusion.com",
"fizil#syncfusion.com", "gowtham#syncfusion.com", "harbajan#syncfusion.com",
"akshara#syncfusion.com", "roshini#syncfusion.com"
];
$('#EmployeeNameSearch').ejAutocomplete({
width: "800px",
dataSource: employeeNameList /*I wanna change this list namebased on the selected category in dropdown*/
});
});
Destroy and reinitialize the plugin in the change event of your select:
You can try something like this:
data = {
employeeName: [
"Abishek Chandrasekar", "Bharat", "Deepak", "Eric",
"Fizil", "Gowtham", "Harbajan",
"Akshara", "Roshini"
],
employeeID: [
"SF1010", "SF2010", "SF3010", "SF4010",
"SF5010", "SF6010", "SF7010",
"SF9010", "SF8010"
],
emaiID: [
"abishek.chandrasekar#syncfusion.com", "bharath#syncfusion.com", "deepak#syncfusion.com", "eric#syncfusion.com",
"fizil#syncfusion.com", "gowtham#syncfusion.com", "harbajan#syncfusion.com",
"akshara#syncfusion.com", "roshini#syncfusion.com"
]
};
$('#searchFilterList').change(function(){
name = $(this).val();
$('#EmployeeNameSearch').ejAutocomplete("destroy");
$('#EmployeeNameSearch').ejAutocomplete({
width: "800px",
dataSource: data[name]
});
});
You should listen on the change event of the Select box using jQuery's on event handler. When the value of select box changes, the relevant data is chosen based on the selected option, and then the autocomplete box is re-initialized with the right data.
(function () {
var employeeNameList = [
"Abishek Chandrasekar", "Bharat", "Deepak", "Eric",
"Fizil", "Gowtham", "Harbajan",
"Akshara", "Roshini"
];
var employeeIDList = [
"SF1010", "SF2010", "SF3010", "SF4010",
"SF5010", "SF6010", "SF7010",
"SF9010", "SF8010"
];
var emaiIDList = [
"abishek.chandrasekar#syncfusion.com", "bharath#syncfusion.com", "deepak#syncfusion.com", "eric#syncfusion.com",
"fizil#syncfusion.com", "gowtham#syncfusion.com", "harbajan#syncfusion.com",
"akshara#syncfusion.com", "roshini#syncfusion.com"
];
function initAutocomplete(data) {
$('#EmployeeNameSearch').ejAutocomplete("destroy");
$('#EmployeeNameSearch').ejAutocomplete({
width: "800px",
dataSource: data
});
}
// when filter box value is changed, re-init
// autocomplete based on selected option
$('#searchFilterList').on('change', function () {
var selectedOption = $(this).val();
if (selectedOption === 'employeeName') {
initAutocomplete(employeeNameList);
} else if (selectedOption === 'employeeID') {
initAutocomplete(employeeIDList);
} else if (selectedOption === 'emailID') {
initAutocomplete(emaiIDList);
} else {
initAutocomplete([]);
}
});
// On page load, initialize autocomplete with employee names
initAutocomplete(employeeNameList);
})();
As you can see from my code, I have taken it from another site.
I would like to add a fourth drop down to the page. It needs to the be first drop down. The type drop down.
The code I have only allows 3 dynamic drop downs, it is basically a state, city and country drop down that I have ammended to suit my needs.
I have added it to a jsfiddle
<tr>
<td width="254" style="text-align: left;">
<p>
Type:
<select name="Type" id="Type">
<option value=""></option>
<option value="Monthly">Monthly</option>
<option value="Annually">Annually</option>
</select>
</p>
<tr>
<td width="254" style="text-align: left;">
Box:
<select name="country" id="country" onchange="setStates();">
<option value=""></option>
<option value="Sky HD">Sky HD</option>
<option value="Sky+">Sky+</option>
<option value="Sky Standard">Sky Standard</option>
</select>
</td>
<td width="252" style="text-align: left;">
<p> </p>
</td>
</tr>
<tr>
<td style="text-align: left;">
Product :
<select name="state" id="state" onchange="setCities();">
<option value=""></option>
</select>
</td>
<td style="text-align: left;">
<p> </p>
</td>
</tr>
<tr>
<td style="text-align: left;">
Price :
<select name="city" type="text" id="city" />
</td>
<td style="text-align: left;">
</td>
</tr>
The Javascript code
/* This script and many more are available free online at
The JavaScript Source!! http://www.javascriptsource.com
Created by: Michael J. Damato | http://developing.damato.net/ */
// State lists
var states = new Array();
states['Sky HD'] = new Array('Platinum', 'Gold', 'Diamond');
states['Sky+'] = new Array('Platinum', 'Gold', 'Diamond');
states['Sky Standard'] = new Array('Platinum', 'Gold', 'Diamond');
// City lists
var cities = new Array();
cities['Sky HD'] = new Array();
cities['Sky HD']['Platinum'] = new Array('£8.49');
cities['Sky HD']['Gold'] = new Array('£7.49');
cities['Sky HD']['Diamond'] = new Array('£6.49');
cities['Sky+'] = new Array();
cities['Sky+']['Platinum'] = new Array('£8.49');
cities['Sky+']['Gold'] = new Array('£7.49');
cities['Sky+']['Diamond'] = new Array('£6.49');
cities['Sky Standard'] = new Array();
cities['Sky Standard']['Platinum'] = new Array('£8.49');
cities['Sky Standard']['Gold'] = new Array('£7.49');
cities['Sky Standard']['Diamond'] = new Array('£6.49');
function setStates() {
cntrySel = document.getElementById('country');
stateList = states[cntrySel.value];
changeSelect('state', stateList, stateList);
setCities();
}
function setCities() {
cntrySel = document.getElementById('country');
stateSel = document.getElementById('state');
cityList = cities[cntrySel.value][stateSel.value];
changeSelect('city', cityList, cityList);
}
function changeSelect(fieldID, newOptions, newValues) {
selectField = document.getElementById(fieldID);
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++) {
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
setStates();
});
The script that this is based on is not ideal if I understand your data model correctly. Besides what is mentioned in comments, the State / City scenario has a hierarchy to it, that does not seem applicable to your use case. The list of products appears to be identical regardless of which box I choose, correct? And the combination yields a unique price?
If so, the script you're starting with differs from your desired result in at least two ways:
There is no point in updating the other dropdowns, when another dropdown changes
You should never be able to select the price at all, so this doesn't need to be a dropdown.
I would begin by defining a readable data source, of all the options and their resulting prices:
var prices = [
{ type: 'monthly', box: 'Sky HD', product: 'Platinum', price: '$ 10' },
{ type: 'monthly', box: 'Sky HD', product: 'Gold', price: '$ 20' },
{ type: 'monthly', box: 'Sky HD', product: 'Diamond', price: '$ 30' },
{ type: 'monthly', box: 'Sky+', product: 'Platinum', price: '$ 40' },
...
];
After that, define the different filters. For each filtered property, I'll assume there exists a select with a corresponding class.
var options = ['type','box','product'];
With that taken care of, iterate over the options, find the unique values for that option in the data source and populate the dropdowns. Also, add an on change listener to each dropdown.
options.forEach(function(opt) {
var drop = document.querySelector('.'+opt);
var unique = Object.keys(prices.reduce(function(x,y) { return x[y[opt]] = 1, x; }, {}));
unique.forEach(function(value) {
var htmlOption = document.createElement('option');
htmlOption.value = htmlOption.innerText = value;
drop.options.add(htmlOption);
});
drop.onchange = function() {
updatePrice();
};
});
All that remains is to define updatePrice, which is called each time any of the dropdowns are changed. We iterate through all properties again, and filter out only the prices that match the current selection. If your data source is set up correctly, that should leave you with exactly one match. You could of course add error handling to this to verify that:
function updatePrice() {
var matches = prices;
options.forEach(function(opt) {
var drop = document.querySelector('.'+opt);
matches = matches.filter(function(price) { return price[opt] == drop.value; });
});
document.querySelector('.price').innerText = matches[0].price;
};
Done. Call updatePrice once to set up the initial value:
updatePrice();
This is assuming your scripts are placed last in body. If they're in head, you need to defer the call to updatePrice, and also the setting up of the dropdowns, until DOMReady.
Fiddle
Update: For IE8 compatibility, convenience functions Array.prototype.forEach has been rewritten as regular for loops; Array.prototype.reduce, Array.prototype.filter and Object.prototype.keys has been replaced with functions that roughly mimics their behavior.
IE8-updated fiddle
My problem is that i have 2 dropdowns and I want to change second dropdown by the value of first. For example: if user chooses "Apple" on the first dropdown second dropdown should instantly get "iPhone" and "iPad" options. If client changes his mind and selects "Microsoft" "iPhone" and "iPad" values should be deleted and instead of them there should appear "Windows" and "Office". How can I make it work? Thanks.
HTML:
<select name="brand" id="brand" onChange="populateSecond(this.value);">
<option value="">----------------</option>
<option value="1">Apple</option>
<option value="2">Microsoft</option>
</select>
<select id="model">
<option value="">----------------</option>
</select>
jQuery:
$(document).ready(function() {
$("#brand").change(function(populateSecond(id)) {
if(id == 1){
$('select[id=model]').append('<option value="a">iPhone</option>');
$('select[id=model]').append('<option value="a">iPad</option>');
}if(id == 2){
$('select[id=model]').append('<option value="b">Windows</option>');
$('select[id=model]').append('<option value="b">Office</option>');
}
});
});
Problem: http://jsfiddle.net/w6E88/6/
Remove the onChange from the html and do it like this!You are already using Jquery onchange no need to give onChange to your HTML also if you need the selected value from the first dropdown you could simply use this.value to get it and make the necessary changes to your Second DropDown List.
HTML
<select name="brand" id="brand">
<option value="">----------------</option>
<option value="1">Apple</option>
<option value="2">Microsoft</option>
</select>
<select id="model">
<option value="">----------------</option>
</select>
JQUERY
$(document).ready(function() {
$("#brand").change(function() {
var id=this.value;
if(id == 1){
$('#model').html("");
$('#model').append('<option value="a">iPhone</option>');
$('#model').append('<option value="a">iPad</option>');
}else if(id == 2){
$('#model').html("");
$('#model').append('<option value="b">Windows</option>');
$('#model').append('<option value="b">Office</option>');
}
else{
$('#model').html("");
$('#model').append('<option value="">----------------</option>')
}
});
});
Here is another jQuery way of achieving the functionality you want (commented with explanation)
Added bootstrap class to select element for the looks.
HTML
<select id="mainCategorySelect" name="mainCategorySelect" class="form-control">
<option>Select category</option>
</select>
<select id="subCategorySelect" name="subCategorySelect" class="form-control"></select>
JS
// Wait for the dom to be ready
$(function () {
// For the sake of this example our business and products are arrays
var businesses = ["Microsoft","Apple"],
msProducts = ["Microsoft Phone","Microsoft Office","Microsoft Windows 10"],
appleProducts = ["Apple iPhone","Apple iPad","Apple iPod","Apple iSomething"],
// Declare variables for the select elements
mainCategorySelect = $('#mainCategorySelect'),
subCategorySelect = $('#subCategorySelect');
// Iterate thorugh businesses and populate the main select element
for (var i = 0; i < businesses.length; i++) {
mainCategorySelect.append("<option value='"+businesses[i]+"'>"+businesses[i]+"</option>");
}
// using jQuery .on('change')
mainCategorySelect.on('change', function() {
// Always clear the sub category select when main select element value is changed
subCategorySelect.empty();
// Retrieve the value of the main select element
var business = $(this).val();
// if else statement to deside which products to list in the sub category select element
if (business == "Microsoft") {
// if Microsoft then iterate through the msProducts array and append the values as option elements to the sub category select element
for (var i = 0; i < msProducts.length; i++) {
subCategorySelect.append("<option value='"+msProducts[i]+"'>"+msProducts[i]+"</option>");
}
} else if(business == "Apple") {
// if Apple then iterate through the appleProducts array and append the values as option elements to the sub category select element
for (var i = 0; i < appleProducts.length; i++) {
subCategorySelect.append("<option value='"+appleProducts[i]+"'>"+appleProducts[i]+"</option>");
}
}
// When the user changes the value of the sub category select element the do something with it
subCategorySelect.on('change', function() {
alert($(this).val());
});
});
});
And here is a working fiddle: http://jsfiddle.net/kagLhpka/
You already have onChange="populateSecond(this.value);" in your HTML code, no need for the .change in JS as well.
You can either define the function populateSecond entirely before the first call to it; or use only the jQuery method. I'm giving the jQuery result here only:
$(document).ready(function () {
$("#brand").on('change', function (id) {
if (id == 1) {
$('select[id=model]').append('<option value="a">iPhone</option>');
$('select[id=model]').append('<option value="a">iPad</option>');
} else {
$('select[id=model]').append('<option value="b">Windows</option>');
$('select[id=model]').append('<option value="b">Office</option>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="brand" id="brand">
<option value="">----------------</option>
<option value="1">Apple</option>
<option value="2">Microsoft</option>
</select>
<select id="model">
<option value="">----------------</option>
</select>
PS: I prefer using .on('change', handler) method over .change.
Here is the structured way.
var childData = {
apple: ["iPhone", "iPad"] ,
ms: ["Windows", "Office"]
};
$("#brand").change(function () {
var newData = childData[this.value];
var element = $("#model").empty();
element.append('<option>----------------</option>');
$.each(newData, function(i, val) {
element.append('<option value='+i+'>'+val+'</option>');
});
});
Check this Fiddle: http://jsfiddle.net/soundar24/w6E88/11/
Using explicit conditionals to validate against will make this difficult to maintain in the future if the product line expands beyond a certain quantity. Using some form of array is a better way to do it, as others have shown.
Also, while jQuery is a great library, don't forget about vanilla JavaScript. When coded well, even though it appears more convoluted, plain JavaScript should run faster than a jQuery counterpart. With that in mind, here's another solution, this time in "more or less" plain JavaScript -- I left in the on ready.
HTML
<select name="brand" id="brand">
<option value="-1">--------------------</option>
<option value="apple">Apple</option>
<option value="microsoft">Microsoft</option>
</select>
<select id="model">
<option value="-1">--------------------</option>
</select>
JavaScript
var products = {
apple: [
{ name: "iPhone 6 Plus", model: "iphone_6plus" },
{ name: "iPhone 6", model: "iphone_6" },
{ name: "iPhone 5s", model: "iphone_5s" },
{ name: "iPhone 5c", model: "iphone_5c" }
],
microsoft: [
{ name: "Windows 10", model: "windows_10" },
{ name: "Windows 8", model: "windows_8" },
{ name: "Office 2015", model: "office_2015" },
{ name: "Office 2014", model: "office_2014" }
]
};
function create_option(text, value) {
var option = document.createElement("option");
var txt = document.createTextNode(text);
option.value = value;
option.appendChild(txt);
return option;
}
function populate_model(selection) {
var select = document.getElementById("model");
var i, l;
if ((selection == -1) || (products[selection] === undefined))
return false;
while (select.lastChild)
select.removeChild(select.lastChild);
select.appendChild(document.createElement("option").appendChild(document.createTextNode("--------------------")));
for (i = 0, l = products[selection].length; i < l; i++)
select.appendChild(create_option(products[selection][i].name, products[selection][i].model));
}
$(document).ready(function() {
var brand = document.getElementById("brand");
brand.onchange = function() {
populate_model(this.options[this.selectedIndex].value);
};
brand.value = -1;
});
I've updated your JSFiddle as well: http://jsfiddle.net/w6E88/13/
I have two drop down that can be manipulate. The second drop down; httpauthmode is manipulated by the value in the first drop down;httprestype.
I want the second drop down; httpauthmode to change to default value when user selected
httpreqtype() == 2; i.e
<option value="0" selected="selected">None</option>
//I want the value = 0 be the default value
Javascript
_self.httpreqtype = ko.observable( httpreqtype );
_self.httpauthmode = ko.observable(null);
Here is my html
<label>HTTP Request Type</label><br/>
<select data-bind="value: httpreqtype" style="width:200px">
<?php
foreach($httpRequestOptions as $key=>$val) {
echo '<option value="'.$val["id"].'" >'.$val["name"].'</option>';
};
?>
//$httpRequestOptions is an array inside my viewModel, I only put a piece of my code
</select>
<label>HTTP Auth Type</label><br />
<select data-bind="value: httpauthmode" style="width:200px">
<option value="0" selected="selected">None</option>
<option value="1">Basic Authentication</option>
<option value="2" data-bind = "visible: httpreqtype() == 2" >Body Encryption</option>
<option value="3" data-bind = "visible: httpreqtype() == 2" >Basic Authentication + Body Encryption</option>
</select>
I try hours googling and already tried subscribe function, set the observable to (null), ("") and many other ways. Can someone expert help me or maybe suggest what method I can try. Really appreciate it and many thanks in advance.
You should approach this very differently. Carefully read the options binding documentation and try to rework your code to that approach. Basically it allows you to data bind the select tag, and have the options rendered dynamically by Knockout.
Something like this:
var Model = function(httpreqtype){
var _self = this;
_self.httpauthmode = ko.observable(null);
_self.httpreqtype = ko.observable( httpreqtype );
_self.httpauthmode = ko.observable(null);
var mode0 = { id: 0, txt: "None" };
var mode1 = { id: 1, txt: "Basic Authentication" };
var mode2 = { id: 2, txt: "Body Encryption" };
var mode3 = { id: 3, txt: "Basic Authentication" };
_self.availableHttpAuthModes = ko.computed(function() {
if (_self.httpreqtype() == 2) {
return [mode0, mode1];
}
return [mode0, mode1, mode2, mode3];
});
}
ko.applyBindings(new Model(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="value: httpauthmode,
optionsText: 'txt',
options: availableHttpAuthModes" >
</select>
<br /><br />Change httpreqtype:
<br /><input data-bind="value: httpreqtype, valueUpdate: 'afterkeydown'" />
Set httpauthmode to '0' (value of None) when httprestype changes to '2':
_self.httprestype.subscribe(function(value) {
if(value === '2') {
_self.httpauthmode('0');
}
});
JSFiddle