0

Hi I have a viewmodel which contains form string in an observable

var viewModel = {
    form: '<label>Name</label>' +
          '<input type="text" name="name">'
          '<label>Name</label>' +
          '<input type="text" name="class">',
};

in html i have used with this viewModel like this;

<em data-bind="html: form"></em>

Here what I want to do is append an validation error msg after label tag using Jquery. But I am not able to do so as form attribute of view Model is always constant. Even if I change the html it goes back again to that constant state. How can I solve this problem please help.

wrufesh
  • 1,379
  • 3
  • 18
  • 36

1 Answers1

1

Not the answer you may want to hear, but posting nonetheless...

You need to rethink your approach.

The html binding is well suited for inserting (trusted) snippets of html content into your application, e.g. some sanitized bit of content from a CMS. It's not well suited for loading more parts of your application, not in the least because bindings are not applied to the new DOM bits.

It seems you're trying to load parts of your application dynamically. Using view models to determine when/which/how to load those parts is a good thing, but the mechanics are better left to other instruments in the KnockoutJS toolbox. Specifically, you should have a look at knockoutjs component for this task. Alternatively, you could use templates instead.

As a footnote, there are a few more specific issues to mention as well:

  • You try to load a form inside an em tag? Beware of what content is and isn't valid or sensical inside such a tag.
  • You want to use jQuery for validation, but you should have a look at ko-validation or some knockout-friendly integration between jQuery-validation and KO;
  • The form property is not observable, so why would you use KO to render it in the first place? Perhaps vanilla js or plain jQuery is a better choice?

Final note, as indicated by OP in comments, if you insist on keeping this approach, there's a different question that contains some solution. See: "data-bind on dynamically generated elements".

Community
  • 1
  • 1
Jeroen
  • 60,696
  • 40
  • 206
  • 339
  • Here I am using ko-validation. Thinking that using both will be the same case I mentioned Jquery.Thanks for the answer but I solved this by reading this stackoverflow post.http://stackoverflow.com/questions/11066732/knockout-data-bind-on-dynamically-generated-elements – wrufesh Jun 15 '16 at 07:33
  • Okay, good to hear you solved your problem. I've taken the liberty of including the link from your comment in my answer as a final suggestion. – Jeroen Jun 15 '16 at 07:52