MVC: Calling Javascript function in View without any HTML control - javascript

I have a view in which I do some condition check when the page load.
if(model.count()>0){
}
I then want to call a javascript function if this condition is satisfied. How can I do this please?
I know how to do that within an html control but can this be done without any control?
Or how can i do this check in the javascript, thus having to refer to the view's model?
EDIT
This is what I have now, but the function is not recognized: The name myfunction does not exist in the current context
<script>
$(document).ready(function () {
#if (Model.Count() > 0)
{
myfunction(Model.parameter);
}
});
</script>
EDIT
I changed that to
#if (Model.Count() > 0)
{
<script type="text/javascript">
$(document).ready(function () {
myfunction(#Model.parameter);
});
</script>
}
But not working. Even if I try something like alert("test" + #Model.parameter) within the .ready(function()), it does not work.
Alternatively, I will have to write the code in the view. I tried eliminating the function and doing it in the view but i will need a way of setting the id property of html element to a variable. something like var variable = Model.param1 and then having <div id=variable></div>. But how can I set the id property to a variable?

well you can simply add the javascript in between the braces. So if you are using Razor
#if(model.count()>0){
<script>
// Javascript code here
</script>
}
What this will do is add the javascript in the page which will then be executed when the browser renders the page.
A good practice would be to execute this code when the whole document is ready. If you are using jQuery, you can do this using $(document).ready(function(){ /*Code goes here*/ });

With JavaScriptModel ( http://jsm.codeplex.com ) you could write the following code in your controller action:
if (list.Count > 0)
{
this.AddJavaScriptFunction("myjavascriptfunction", parameter);
}
You would not need to modify your view and you won't have any inline obstrusive javascript.

You could use a non-rendering html element (e.g a hidden Div) and write out the value of model.count, or even true/false to signify whether model.count > 0 into that hidden element. Then in your JavaScript you can obtain the value from the hidden element and run the condition.
Obviously this isn't appropriate if there are security implications with applying the condition. If this is the case then 'bPratik's suggestion would be more appropriate.

Try putting the if statement outside of the script tag like this
#if (Model.Count() > 0)
{
<script type="text/javascript">
$(document).ready(function () {
myfunction(#Model.parameter);
});
</script>
}

Related

check if dynamically inserted input field exists

I have a script that adds a button that will open up a window that allows us to design t shirts. All i have top do is include their script and the button gets automatically added.
Below is the code which is dynamically added to the page.
<input id="design_edit_btn" class=" btn btn-success btn-block" value="Edit the design" type="button">
What i need to do is that, if that button is available then show a message saying its customizable or else display cannot be customized.
I tried the below code
if($("#design_edit_btn").length) {
alert("exists");
}
I did a bit of research but couldn't find a way to achieve this. Can someone please let me know how this can be done?
Thanks
You probably need to wait until the script has been loaded and executed.
Try waiting when the document is finished and do something like this:
jQuery(($) => {
if($("#design_edit_btn").length) {
alert("exists");
}
} );
jQuery triggers a given callback as soon as the document is ready. If that doesn't work either you could try adding a setTimeout as well.
Since the button you look for is create by an external script, that script is likely not finished by the time the DOM is ready, hence you won't find it, not even at $(document).ready()
What you can try is to use the script tag's onload, and when it fires, check for the button, like I do here, fire a console.log when jQuery have loaded.
Note, the order of the script is important
Stack snippet
<script>
function checkForjQuery() {
console.log('jQuery loaded');
}
function checkForButton() {
if ($("#design_edit_btn").length) {
alert("exists");
}
}
</script>
<script onload="checkForjQuery()" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- temp. commented out
<script onload="checkForButton()" src="your_script_path"></script>
-->
have you tried something like this:
if(document.getElementById('design_edit_btn') != null)
{
alert("exists");
}
This should do the trick
if ($("#design_edit_btn").length > 0) {
alert("exists");
}

load jquery function before content

i made this function:
var jq111 = jQuery.noConflict();
if (jq111("#tab-upsell_tab").find("div").length > 0){
} else {
jq111(".upsell_tab_tab").hide();
jq111("#tab-upsell_tab").hide();
}
This hide a element if are empty.
But on page load, #tab-upsell_tab appear for 1 second (if need to be hide) and i don't like it.
There is a way to load this function before this element? Or something similiar.
Edit: i accept a css solution, but how?
You should set .upsell_tab_tab and #tab-upsell_tab to display: none in your CSS. Change your JavaScript to this also:
var jq111 = jQuery.noConflict();
if (jq111("#tab-upsell_tab").find("div").length > 0){
jq111(".upsell_tab_tab").show();
jq111("#tab-upsell_tab").show();
}
This way your elements are hidden by default, and you must imperatively show them based on your logic.
Try using $.holdReady() , .ready()
$(window).load(function() {
var jq111 = jQuery.noConflict();
jq111.holdReady(true);
if (jq111("#tab-upsell_tab").find("div").length > 0) {
} else {
jq111(".upsell_tab_tab").hide();
jq111("#tab-upsell_tab").hide();
}
jq111.holdReady(false);
jq111(document).ready(function() {
// do stuff
})
})
div .length within "#tab-upsell_tab" not greater than 0
http://plnkr.co/edit/Xp2RbPe65BaFeobtTVOL?p=preview
div .length within "#tab-upsell_tab" greater than 0
http://plnkr.co/edit/ekSUelSinlM8baKQe74Y?p=preview
The DOM renders HTML, CSS, then JS. So if you want your HTML elements hidden then hide them with your CSS or you could create using a template system like mustache or in your JS code. I prefer creating them in your JS code. It makes your code cleaner and it lighter on the DOM.

How to guarantee that a script in the middle of the body runs after all the DOM has finished load

In my <body> I have a component that inserts a script that is supposed to run only after all the page has completely loaded:
<script>
$('<script id="smallPlacarScriptdId">\
$(window).load(function() {\
$(".main.right").hide();\
$("#rightzero").show();\
$(".comp.smallPlacard.firstChild").click(function () {\
var clicked = $(this).parent().attr("id");\
$("main.right").hide();\
$("#right"+clicked+"").show();\
});\
})\
<\script>').appendTo("body")
</script>
That's not happening and this script (1) is correctly inserted into the DOM but (2) is not working (not hiding .main.right nor showing #rightzero).
I though that by using this approach I would guarantee that it would be the same as just put this script at the bottom of the <body> but it isn't. In fact if I put it (not dynamically like this) in my page it produces the desired result.
I tried setTimeout() to validate my theory but I'm getting an error in jQuery and I'm lost.
That might be the problem:
<\script>').appendTo("body")
Browser might think you are actually closing your script tag. Change it to
</' + 'script>').appendTo("body")
Check this plunker out: http://plnkr.co/edit/Oc6yrFMdPoW2WV257CBQ?p=preview
Just use this code
<script id="smallPlacarScriptdId">
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
})
</script>
Sorry I didn't read you question well enough.
Javascript will allow you to access undeclared variables, so use that to your advantage. Check if a variable is set, undefined is treated as a false so no need for initialization. As soon as you enter the code just set it to true so nothing else will execute.
Hopefully this solves the problem for you, but you really should look at from the server avoiding the javascript, it will bloat the page.
<script>
if (!myScriptHasLoaded)
{
myScriptHasLoaded = true;
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
});
}
</script>

How to make a div onload function?

I want to load an HTML page as a div inside my webpage by removing its HTML and body tags. But the HTML page has a <body onload=" ... " > , I need this function to continue working. Seems <div onload=" ... " > is not working. How can I insert this onload function into my website's body (on this page only) without directly editing my original website code (php)?
Have you used jQuery before? If so, just get the id of your div (let's say "SomeDiv") and then use the "ready" method like this:
$("#SomeDiv").ready(
function(){
//do stuff
});
you can use jQuery.load to load the contents of the page into your div
$(document).ready(function() {
$("#containing-div").load("[url of page with onload function]");
});
the code above goes in the page that contains the div. the page with the onload function doesn't get changed.
You can add an additional Javascript tag at the end of the loaded page (once inserted inside the div) which will executing as soon as it's loaded. Like this:
<div>
Insert the inner html content of that pages here and add this script at the bottom and add the onload function of the original html to this script.
<script type="javascript">
alert("hello world");
</script>
</div>
Just remember to have the javascript available to your page. What I mean is that if the javascript function called which is called inside onload="..." is defined in the <head> of the loading html document and you're throwing the <head> out then this won't work.
Not the best but one way is to check the div periodically if it's loaded:
var myInterval = setInterval(function () {
if ($('.mydiv') && $('.mydiv').width() > 0) {
// write your logic here
clearInterval(myInterval);
}
}, 3000);
If you want to add the onload event on a div, you cannot, but you can add onkeydown and trigger the onkeydown event on document load.
<div onkeydown="setCss();"></div>
$(function () {
$(".ccsdvCotentPS").trigger("onkeydown");
});

Writing javascript with jquery and using a variable

As a javascript newbie, I am struggling to use a script with a variable that runs a bit of JQuery (and also struggling to use the right language here, I'm sure!)
The action I want to happen is to change the CSS class of a specific div, e.g. #det90, for which I have the following code (I have used the same on a $(window).load(function() and it works on a different set of divs):
$("#MYDIVIDHERE").switchClass("sdeth","sdet",50);
So I wrote the following:
<script type="text/javascript">
$(function revealCode(divID) {
$("#divID").switchClass("sdeth","sdet",50);
})
</script>
and called it from an anchor with:
onClick="revealCode('det90');"
I think the problem is that I don't know how to write the script and pass the variable in the brackets (divID) to the next line (where I've got "#divID"). Any help or pointers to tutorials gratefully received!
Solution
Thanks to all, but particularly to Caleb. I've scrapped the general function and the onClick, added an ID to the anchor and inserted the following for that anchor (and then repeated that for each anchor/div combination I want to use it on ... and it works :D
$("#linkID").click(function() {
$("#divID").switchClass("sdeth","sdet",50);
});
Change your code to: onClick="revealCode('#det90');"
$(function revealCode(selector) {
$(selector).switchClass("sdeth","sdet",50);
})
jQuery is powered by "selectors" -- similar to CSS syntax.
Don't quote your variable name. Just quote the "#" prefix.
<script type="text/javascript">
$(function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
})
</script>
Change to:
<script type="text/javascript">
function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
}
</script>
You don't need $() around the function
$("#divID") will look for an element with the ID divID, and not what was specified in your function parameter
This won't work. revealCode is local to that scope and not known outside. Also, you're not using the argument you've passed into your handler.
If you're using jQuery, use it to bind to the handler as well like this:
jQuery(document).ready(function() {
function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
}
jQuery("#divID").click(function() {
revealCode('det90');
});
});
Move your onclick event handler attachment into javascript code. You should try not to mix your functional code with your html.
Anonymous version:
$('#myDiv').click(function () {
$(this).switchClass("sdeth","sdet",50);
});
Normal version:
var myFunction = function (element) {
$(element).switchClass("sdeth","sdet",50);
};
$('#myDiv').click(myFunction, {element: this});

Categories

Resources