I have an ASP.net MVC2 site that I have designed. I have a small design issue. I want a button to change when the view loads. For instance when a certain variable equals a certain value I want one button to show up and another button to disappear. What I have so far is basically a jquery implementation of that idea. But so far, my jquery code is not getting called (I have a debugger statement set inside the jquery so I know it’s not getting called). I have tried to place the code in a $(document).ready(function()… and a $(document).load(function()…
the code still doesn’t load. here is what I tried.
$(document).load(function(){
var $b = <%=toggle %>;
var buttonTog = $("#test1");
var buttonTog1 = $("#Submit1");
if($b=="1")
{
debugger;
buttonTog1.css({
display: 'block'
})
buttonTog.css({
display: 'none'
});
}
else if($b=="0")
{
debugger;
buttonTog1.css({
display: 'none'
})
buttonTog.css({
display: 'block'
});
}
});
$(document).ready(function () {
//debugger;
ShowMessage();
(function () {
var $b = <%=toggle %>;
var buttonTog = $("#test1");
var buttonTog1 = $("#Submit1");
if($b=="1")
{
debugger;
buttonTog1.css({
display: 'block'
})
buttonTog.css({
display: 'none'
});
}
else if($b=="0")
{
debugger;
buttonTog1.css({
display: 'none'
})
buttonTog.css({
display: 'block'
});
}
});
...
});
What I intend to do is check the value of a variable that I get from a ViewData field, and based upon what that value is make the css display attribute of one button or the other be either none or block depending upon circumstances of course. What is the best way to get Jquery code to run when a page first fires? And how would you implement such a scheme? Is this the best way to get this done, or should I consider redesigning how I implement this feature? Thank you for your time.
Let’s try to clean your code a little. Let’s suppose that toggle is a boolean variable defined previously in the page although this is bad and you should use view models:
But assuming you have this information on the server (and you have it since you are defining the toggle variable on the server) I would recommend you directly applying the corresponding CSS classes to the given buttons on the server. This way you don’t even need to use any javascript at all. Simply:
where
ToggleClasswould be a custom HTML helper returning the correct CSS class name based on the parameter value:and finally in your CSS file: