MVC Add HTML with MvcHtmlString.Create but with JavaScript functionality - javascript

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

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.

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?

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
});

Related

How to use Javascript to change href and html text?

So I've got this little piece of HTML that I have zero access to, and I need to change the URL of where it's linking, to somewhere else.
Now I've looked around, and I've tried different approaches and non seem to work so I must be doing something wrong.
the Html code:
<div class="manageable-content" data-container="edit_register_ind_container">
<a class="entry-text-link secondary-step step-button" id="register_ind_container" href="oldurl">Register</a>
</div>
First I wanted to try something that seemed easier, which was to change the displayed text "Register" to "Start a Fundraiser"
This is what I have got for that part:
// url manipulation
$(document).ready(function(){
$("#register_ind_container").click(function(){
$("#manageable-content a").text('Start a Fundraiser');
});
$("#register_ind_container").attr("href", "http://google.ca");
});
No luck so far for any of it.
a little background information:
I am using a platform called Luminate/Blackbaud, its a CMS with a weird set up. header tags and stuff like that go in a different place than the html body and the css is somewhere else as well (but I'm just using ftp to reference it in the header).
How I'm referencing the javascript code.
<script type="text/javascript" src="../mResonsive/js/urlmanipulation.js"></script>
My css works so I'm certain this should to, but I just don't know why it isn't.
All suggestions welcome (except for asking for the html access because I have, 3 weeks ago lol)
Thank you for your time!
I saw your both code :
$("#register_ind_container").attr("href", "http://google.ca");
This line will execute on page load so href should be changed on load
$("#register_ind_container").click(function(){
But when you performing this click on Id
it wont work because at that instance this id associated with an hyperlink
so hyperlink having the default subset rules
for Overriding this you can try
$("#register_ind_container").click(function(e){
// custom handling here
e.preventDefault();
$(this).text('Start a Fundraiser');
});
But this is also not a Good Practice. Hope this helps !
$(document).ready(function(){
$("#register_ind_container").click(function(){
$(this).text('Start a Fundraiser');
$(this).attr("href", "http://google.ca");
});
});
You are changing the URL outside the click event.. Wrap it inside the click event.. Also make use of $(this)
// url manipulation
$(document).ready(function(){
$("#register_ind_container").click(function(){
$(this).text('Start a Fundraiser').attr("href", "http://google.ca");
});
});

jQuery Find and Append/Prepend to existing javascript

I have read many of the articles on using jquery to find and append. I have been successful at doing this on other projects, but mostly appending to a div element. I need to append to javascript on the page that unfortunately I don't have core access to.
Existing JS:
<div class="widget">
<script type="text/javascript">
var widget37 = new VideoWidget("VideoCanvas",
"divVideoCanvas37", "DS37");
widgetVideoCanvas37.SetWidth("630");
widgetVideoCanvas37.SetHeight("355");
widgetVideoCanvas37.SetVariable("isMute", "false");
widgetVideoCanvas37.RenderWidget();
</script>
</div>
Before the RenderWidget, I need to add
widgetVideoCanvas37.SetVariable("isAutoStart", "true");
I've tried something like this:
$( "widgetVideoCanvasDS37.RenderWidget()" ).prepend( "<p>Test</p>" );
but it does appear to be working. Maybe prepend isn't the best way to do this. Thanks in advance for the help!
The element would be selected like $('script').appened('blah');
But i feel that that probably won't or shouldn't work. That be a very large security flaw if i was able to run my own script locally to append JavaScript to the script element of another page that i don't have core access to.

jQuery .before() with external HTML file (same domain)

I'd like to know if it's possible to use the .before() function in jQuery to load an external html file in the same domain.
What I'd like is an HTML form with dynamically placed form elements based on users' entries (being able to add as many phone number fields as they want for instance). I tried many options like .load() or .html() but I can't seem to find any working solution. Maybe I'm not doing this right...
<script>
$(document).ready(function(){
$("#add_society_number").click(function(){
$(this).closest('table').before(forms/society_phone_number.html);
});
});
</script>
What should I use instead of "forms/society_phone_number.html"?
I'll have many pages with shared forms, that's why I want them in external files.
Another reason why I'd like to load external HTML files is that when using .before() function, I have to use "\" for each line breaks in my code...
Thank you :)
You'll need to use $.ajax or one of it's helper methods to get the content.
$(document).ready(function(){
$("#add_society_number").click(function(){
var self = this;
$.get("forms/society_phone_number.html",function(response){
$(self).closest('table').before(response);
});
});
});
you can also use .load('/url/to/script')
<script>
$(document).ready(function(){
$("#add_society_number").click(function(){
$(this).closest('table tbody').load('forms/society_phone_number.html');
});
});
</script>

how to re-factor/extract methods to separate file for re-use

I'm fairly new to the whole JQuery/javascript world, but I've managed to wack together a working jqgrid with a datepicker & custom control (used jquery auto complete) based on code samples i found on the net. I've added the code to a T4 template in my project as it'll probably act as a base/starting point for most pages. (Side note. I'm using asp.net MVC)
JFIDDLE: LINK
1.) I'd like to move the initDateEdit & initDateSearch to the same function (using a parameter, to disable/enable the showOn property) as they are basically similar.
2.) How would be the best way to set nonWorkingDates from outside the new function/file. same applies to the autocomplete_element (I'd like to specify the url)
Changing
"function nonWorkingDates(date)" to => "function nonWorkingDates(date, nonWorkingDates)"
isn't working, (guess it's got got something to do with how its gets called "beforeShowDay: nonWorkingDates")
Thanks in advance!
If you have a chunk of JS code like this:
<script type="text/javascript">
... code goes here ...
</script>
You simply copy the whole thing, eliminate the containing script tags, and save the raw code
... code goes here ...
to a file, which you then include with:
<script type="text/javascript" src="yourfile.js"></script>
However, since you're using jquery, you'll have to make sure that this above snippet is placed AFTER the script tag that loads up jquery, or you'll get a "no such function" syntax error.

jQuery objects don't work

When I store a jQuery object in a variable, like this:
var $myObject = $("div#comments");
...I can't use the object $myObject!
This is what I'm doing to change the html of div#comments:
$myObject.html(data);
It does nothing. I already tried this way too, this time to select an element inside div#comments:
$("div.comment", $myObject);
It doesn't work.
I just want to be able to save an element in a variable and then use it!
Note: some people don't put $ before the variable name, like this: myObject.
Are you calling it after the document is loaded?
// This will ensure that the code doesn't run until
// the document has loaded
$(function() {
var $myObject = $("div#comments");
});
(This is a shortcut for jQuery's .ready() method.)
http://api.jquery.com/ready/
As long as the document is loaded, and you have a <div> with the ID comments on the page when it loads, it should work.
Also remember that there can only be one element on the page with any given ID. Because of this, it is actually a little better (quicker) to do $("#comments"); instead of $("div#comments");.
You've only provided snippits of your code, so it is impossible to tell for sure, but the odds are that you are running the code in a <script> element that appears before the <div> element and don't do anything (such as use the ready event) to delay the execution of the code until the div exists.
The result is that you get a jQuery object which found no elements. Move the script element so it is after the div. Just before the end tag for the body is a good place.
The syntax is perfectly valid and should work. Are you dynamically appending the comments div? You should alert( $myObject.length ) to see if it's 0 or 1, if its 0 that means it's never picked up.
You may need to bind the var statement until after dom ready, window load, or your ajax callback.
Well, that syntax is perfectly fine so something else is going on. Can you show your markup? And what do you get if you add an alert($myObject.length)? And one last thing to check... are you running this inside an on-ready handler?
Ok, thanks everyone for that.
I got the solution.
I thought about the order the things were loaded in the DOM and found the solution.
The problem (with the markup) was:
<div id="comments">
<script type="text/javascript">
loadComments(params);
</script>
</div>
The code above was written by PHP!
So it executed the function as soon as the browser read the code.
I already tried to put the script on the end of the page, after the function was called. The funcion was not defined yet.
So, the funcion loadComments should be executed after the div was ready AND after the function was defined.
I wrapped the code between the tags with a .ready(), like this:
<script type="text/javascript">
$(function() {
loadComments(params);
});
</script>
It was a distraction.
Sorry everyone!
Thanks a lot.
If you have the same problem and you didn't understand what I did, ask me. XD

Categories