amelian
amelian

Reputation: 446

MVC Add HTML with MvcHtmlString.Create but with JavaScript functionality

I have a big doubt. In a MVC project, I render a HTML template (loaded from .html file) into a View with MvcHtmlString.Create();

This works fine but have a problem. This HTML template need to do javascript functionality, the problem? That this don't work, because the HTML is rendered after the javascript and the js functionality not work.

Something like this:

<script type="text/javascript">
$(document).ready(function(){
    $("#SomeID").click(funciton(){
        //This don't work because the #SomeID not exists yet 
    });
});
</script>
<br />
@MvcHtmlString.Create(@Model.HTMLTemplateContent);

Someone can help me about this or tell me something at respect?

Thanks

Upvotes: 1

Views: 1047

Answers (3)

amelian
amelian

Reputation: 446

Thanks! I not have idea about this.

Is possible to access at elements by the same "method"? How to do to get this? i.e

I'm using jSignature to implement sign en the document.

whit this:

$("#someDivID").jSignature();

I'm using now to access at div element with this:

var signCanvasOn = document.getElementById("someID");
signCanvasOn.jSignature();
signCanvasOn.jSignature("reset");

But this don't work for me, only work if I use:

$("#someID").jSignature();
$("#someID").jSignature("reset");

What is the real problem?

Upvotes: 1

Gaz Winter
Gaz Winter

Reputation: 2989

Have you tried adding the jquery at document level?

That's how i usually ensure that jquery continues to work with any stuff i load on the page dynamically.

Something like this:

  $(document).on("click","#SomeID",function()
  {
  //This don't work because the #SomeID not exists yet 
  });

Upvotes: 0

Shyju
Shyju

Reputation: 218732

Use jquery on method.

$(document).ready(function(){
    $(document).on("click","#SomeID",function(){
        alert("Working");
    });
});

on method will work for current and future (Any thing injected to DOM later (Ex : through javascript code, ajax) elements.

Upvotes: 1

Related Questions