1

So i have displayed two input fields the user can enter information in them. I also have another button "add" that allows the user to add another set of two input fields to enter data.

This is my current view of the what i have but i need to add the functionality of adding input fields into my viewModel so it is available upon user click.

jsFiddle of html

I would like to add the functionality of clicking the add button to be placed in like:

self.addName = function(){//return new input fields to user}

and in my html i would have <a href="#" onclick="addName()">

1
  • You didn't share any of your viewModel code... What have you tried? Commented Oct 21, 2015 at 17:17

1 Answer 1

2

The thing is, you need to have observables in array to bind to multiple inputs. You do it like this:

<div class="addNames">
    <!-- ko foreach: ViewModel.values -->
    <div class="fname" >
        <input data-bind="value: $data.value" placeholder="Add your fname..." contenteditable/>
    </div>
    <!-- /ko -->
</div>
<div class="addBtn">
    <a data-bind="click: ViewModel.addValue"> Add Name</a>
</div>

And JS:

 ViewModel = {
        values: ko.observableArray([
            {value: ko.observable('initial value')}
        ]),
        addValue: function(){
            ViewModel.values.push({ value: ko.observable('')});
            ViewModel.values().forEach(function(data){
                console.log(data.value());
            });
        }
    }

    ko.applyBindings(); 

https://jsfiddle.net/x5wu7gsy/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.