0

I need to set an 'input hidden' form element with an array generated from a knockout computed, to send it to the server within the form.

<input type="hidden" name="CourseSubjects" data-bind="value: allSelectedCourseSubjectsIds"/>

in my ViewModel:

self.allSelectedCourseSubjectsIds = ko.computed(function () {
        var result = [];
        for (var i = 0; i < self.CourseSubjects.length; i++) {                
            result = result.concat(self.CourseSubjects[i]().selectedCourseSubjects());
        }       

        return result;
    },self).extend({ rateLimit: { method: "notifyWhenChangesStop", timeout: 1000 } });

where self.CourseSubjects is an array of observable objects that contains a selectedCourseSubjects' observable array.

But the problem is that the hidden input's value is a string with a comma-separated list of Ids, while what i need is a string representation of the array. I mean, what i get as input hidden is:

<input type="hidden" name="CourseSubjects" value="1,2,3"/>

and what i need is

<input type="hidden" name="CourseSubjects" value="[1,2,3]"/>

Thank you.

2 Answers 2

1

The value of a binding can be a JavaScript expression.

data-bind="value: '[' + allSelectedCourseSubjectsIds() + ']'"/>
Sign up to request clarification or add additional context in comments.

Comments

0

How about overriding the toString method for Array?

Something like this:

Array.prototype.toString = function arrayToString() {
  var result = '';
  for (let i=0; i<this.length; i++){
     if (i !== this.length-1)
     { 
       result = result + this[i] + ', ';
     }
     else 
     {
        result = result + this[i];
     }
  }   
  return '[' + result + ']';
};

Note: this will make all Arrays appear this way when toString is called.

https://jsfiddle.net/aLot9aoc/30/

1 Comment

It is generally considered a bad practice to extend/override methods on built-in types. Mainly because you can never know whether other libraries used by your app rely on the default implementation.

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.