Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6390379
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T03:32:30+00:00 2026-05-25T03:32:30+00:00

I’m having some issues with a drop-down list where I need to pass the

  • 0

I’m having some issues with a drop-down list where I need to pass the initial value to the view model so, the drop-down list will be populated with an already-selected value.

This is as far as I got (see this fiddle):

var additionalTravellersDetails = [
    { id: 1, firstName: "George", middleName: "", lastName: "Washington ", AcNum: "12345678" }, 
    { id: 2, firstName: "Abraham ", middleName: "", lastName: "Lincoln", AcNum: "23758383" },
    // etc
];

function Traveller(id, AcNum) {
    this.id = ko.observable(id);
    this.categoryId = ko.observable();
}

Traveller.prototype.getUniqueCategories = function () {
    var thisCategoryId = parseInt(this.categoryId(), 10);
    return ko.utils.arrayFilter(additionalTravellersDetails, function (additionalTravellersDetails) {
        return (additionalTravellersDetails.id === thisCategoryId) || !viewModel.usedCategoryIndex()[additionalTravellersDetails.id];
    });
}

var viewModel = {
    TravRows: ko.observableArray([]),
    addTravRow: function () {
        this.TravRows.push(new Traveller());
    },
    removeTravRow: function (Traveller) {
        this.TravRows.remove(Traveller);
    },

    noOfTrav: ko.observableArray(['1', '2', '3', '4', '5', '6', '7', '8', '9']),
    SelectedNo: ko.observable('1')
};

viewModel.usedCategoryIndex = ko.dependentObservable(function () {
    var result = {};
    ko.utils.arrayForEach(this.TravRows(), function (Traveller) {
        var cat = Traveller.categoryId();
        if (cat) {
            result[cat] = 1;
        }
    });
    return result;
}, viewModel);

viewModel.TravRows.push(new Traveller());

ko.applyBindings(viewModel);

// On Num of Trav Select index change
$("#nrTravelers").change(function () {
    var len = viewModel.noOfTrav().length;
    for (var i = 0; i < len; i++) {
        viewModel.removeTravRow(viewModel.TravRows()[0]);
    }
    for (var i = 0; i < $(this).val(); i++) {
        viewModel.addTravRow();
    }
});

And this is the corresponding view:

<p>Number of travellers:
    <select id="nrTravelers" data-bind="options: noOfTrav,  selectedOptions: SelectedNo"></select>
</p>
<table data-bind="template: {name:'AdditionalTravelersTemplate', foreach: TravRows}"></table>
<script id="AdditionalTravelersTemplate" type="text/html">
    <tr>
        <th>Traveler<span>1</span></th> //TODO: replace 1 with the auto num
    </tr>
    <tr>
        <td>
            <select data-bind="options: getUniqueCategories(), 
                               optionsText: function(item) {
                                   return item.lastName+ ' , ' + item.firstName+ ' - '+ item.AcNum }, 
                               optionsValue: 'id', 
                               optionsCaption: 'choose one...', 
                               value: categoryId"></select > 
        </td>
    </tr >
</script>

The following are the things I need in the above code:

  1. I want to pre populate all the drop-down lists with already selected values
  2. When the list does not contain any more travelers, I want to display some text in the drop down list
  3. I want to add a number after “Traveler” text for each drop-down list

The 2nd requirement I have solved, two more to go.

PS. I have hard coded some part for the first requirement, please tell me if the approach is OK?

Any suggestions/ideas please?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T03:32:31+00:00Added an answer on May 25, 2026 at 3:32 am

    Here are a couple of ideas here: http://jsfiddle.net/rniemeyer/P6aDk/

    For the index, you could either use {{each}} from jQuery template’s or an easy way to still get the benefits of KO’s foreach is to create a manual subscription to your observableArray and update/create a property to hold the position. This would be like:

    viewModel.TravRows.subscribe(function(currentValue) {
        for (var i = 0, j = currentValue.length; i < j; i++) {
           var row = currentValue[i];
            if (!row.position) {
               row.position = ko.observable(i+1);  
            } else {
               row.position(i+1);   
            }  
        }
    });
    

    Now, each row will have a “position” observable that you can bind against and they will stay updated as the array changes.

    For, adding/removing rows, you could add a subscription against the SelectedNo observable and when it changes you can reconcile the actual number of rows. Like:

    viewModel.SelectedNo.subscribe(function(newValue) {
        var actualLen = viewModel.TravRows().length,
            expectedLen = parseInt(newValue, 10);
    
        if (actualLen < expectedLen) {
            for (var i = actualLen; i < expectedLen; i++) {
               viewModel.addTravRow();  
            }
        } else {
            for (var i = actualLen; i > expectedLen; i--) {
                viewModel.removeTravRow(viewModel.TravRows()[i]);
            }
        }
    });  
    

    For setting existing data, I changed the value binding on the dropdown for each row to bind against the id. Then, I set the initial data to include two Travellers with their ids. You could switch this to account number or whatever is appropriate.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I need a function that will clean a strings' special characters. I do NOT
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I need to clean up various Word 'smart' characters in user input, including but
I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I have thousands of HTML files to process using Groovy/Java and I need to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.