TimK TimK - 4 months ago 8
Javascript Question

body onload=func works in IsPost but not !IsPost (are multiple body-onloads okay)?

I have a script that is triggered with an If(IsPost) and an If(!IsPost). When I F11 through the code everything works the same expect at the end a javascript function to show a div does not trigger.

// SCRIPT FOR SHOW DIV.
<script>
function ShowFunction(divId)
{
$("#" + divId).show(600);
}
</script>

if (!IsPost)
{
var user = WebSecurity.CurrentUserId;
var dbCommand = "SELECT * FROM Survey WHERE survey_id = @0";
var row = db.QuerySingle(dbCommand, user);
if (row != null)
{
surv1 = row.surveyQ1;
if (surv1 != null)
{
someOtherVariable = "Complete";
<body onload="$('#somediv').remove();"></body>;
}
}
if (someOtherVariable = "Complete";
{
<body onload="ShowFunction('Mydiv');"</body>;
}
}

if (IsPost)
{
if (Request.Form["btnsubmit"] !=null)
{
var user = WebSecurity.CurrentUserId;
var dbCommand = "SELECT * FROM Survey WHERE survey_id = @0";
var row = db.QuerySingle(dbCommand, user);
if (row != null)
{
surv1 = row.surveyQ1;
}
if (surv1 == "yes")
{
<body onload="ShowFunction('Mydiv');"></body>;
}
}
}


Also, the cshtml page is structured with the script right above the !IsPost which is above the IsPost, which is above the Form code. Another post suggest that a 'window.onload' script, which I also have in my script block, might be messing with the < body onload="func" >. I'm not sure why that would be an issue only when not posting though.

Answer

I found the culprit. Although this wasn't in the original code I posted, I actually had one more body-onload bit of code right above the one that wasn't triggering in the if(!ispost). That extra body-onload wasn't in the if(ispost) which is why the post worked fine. I've edited the original code to show this. Once I moved that first body-onload (with some massaging) down into the other body-onload it worked fine. After moving that first body-onload down I am left with one body-onload in my if(!ispost) section of code.

<body onload="ShowFunction('Mydiv'); $('#somediv').remove();"</body>;                

I also added appended my original title so that this might be useful for someone who stumbles upon it. In sum, watch out when you have multiple onload events. You might need to stack them into one onload and massage the code a bit.