Run Javascript After Page Load - c#

I understand there are MANY posts on this, but I have tried every single one and none of them work!
I have an aspx and aspx.cs page being run using visual studio 2010.
on my aspx page I have a table
<table id="viewPendingTable" runat="server"></table>
On the aspx.cs page, the table is loaded with data. This works fine, No Problem. Once the page is loaded, the table contains the dynamically added data I require.
I am using jquery dataTables to style my table using the standard
$(document).ready(function () {
$('#viewPendingTable').dataTable({
"bJQueryUI": true,
});
});
When I create a test table with dummy information directly into the html, the data table displays correctly as required. But when I apply The jquery script to the dynamic table. Nothing happens. The dynamic data is displayed as required, but the data table (search functions, style etc) are not present.
Now I suspect this is because the scripts are run before the table is populated with data.
This is where I began my mission to force the jquery/javascript to run AFTER the aspx.cs has run and the table has been populated.
But I failed... So just as a test I thought I'd run an alert('YAAY'); from the c# side using registered start up scripts. but to no Avail that wouldnt work.
So can somebody PLEASE tell me why this isn't working.
I've tried Multiple Different ways of startup scripts!
My aspx is:
<table id="viewPendingTable" runat="server"></table>
<script type="text/javascript" language="javascript" id="ShowTable">
<!--
loadTable();
function loadTable() {
$(document).ready(function () {
$('#viewPendingTable').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});
alert('ALEX');
document.getElementById("table_id").width = "100%";
}
//-->
</script>
And my aspx.cs is:
protected void Page_Load(object sender, EventArgs e)
{
loadMyTable();
ClientScriptManager a = null;
a.RegisterStartupScript(GetType(), "anotherkey", "alert('ASDFASDFASDF');", true);
a.RegisterStartupScript(GetType(), "anfgsdgsderkey", "alert('MOTHER');", false);
a.RegisterStartupScript(this.GetType(), "AKey", "loadTable();", true);
ClientScript.RegisterStartupScript(GetType(), "MyScript", "<script language=javascript>" + "alert('Hello ASP.NET'); }</script>");
ScriptManager.RegisterStartupScript(this.Page, GetType(), "script", "alert('Success!');", true);
Page.ClientScript.RegisterClientScriptBlock(GetType(), "script", "alert('AAA');", true);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script",
"alert('a');" +
"$(document).ready(function (){" +
"$('#viewPendingTable').dataTable({" +
"\"bJQueryUI\": true" +
"\"sPaginationType\": \"full_numbers\"" +
"});" +
"}); alert('b'); document.getElementById('viewPendingTable').width = 100%", true);
}
I have tried more methods for trying to run javascript after page load but they were lost in the anger of failing so badly.
Somebody PLEASE HELP!
Why aren't my simple javascript alerts running?
Even if I got them to work... would the data table be correctly styled by executing the jquery after page Load???
Thankyou Kindly for your time
Alex
p.s. No comments on asp:gridView or asp:DataTable as That Failed EPICALLY and i posted a question on it days ago and nobody has replied. If you care to take a look
CLICK HERE

Change this line of code and try
"$('# " + viewPendingTable.ClientID + "').dataTable({" +
in you document.read script that you have written
Its because you can get acutal ID of the table control when the page get render on the browser
Edit
Make use of
RegisterStartupScript because it emits your JavaScript at the end of the page just before </form> tag (before the <form> tag ends).

The most likely issue you're facing is that id="viewPendingTable" doesn't exist on your page.
By adding the runat="server" attribute on your table, the ID will be changed so that ASP.NET can bind to it on postback.
You'll need to use the ClientID property of the table in your jQuery:
viewPendingTable.ClientID

First of all, client side code is ALWAYS run after the server side code is executed. Although client side code can be run before the html is rendered in your browser. So this has nothing to do with that.
If you check the generated html, you will see that asp.net will generate the id's voor the element to which you apply the runat attribute. To solve this, add a class to the table and change your js selector to $(".classname").
Extra tip: Use a debugger like firebug which allows you to debug your js code, which makes it easy to solve problems like these :)

Related

accessing checkbox from asp.net formview in javascript

I have a checkbox in my formview which I want to access in JS to do some enable/disable for textboxes.
This is what I have:
<script type="text/javascript">
$(document).ready(function () {
$('#<%=FormView1.FindControl("chkMap").ClientID%>').change(function () {
if ($(this).is(":checked")) {
}
$('#textbox1').val($(this).is(':checked'));
});
});
With this code, nothing happens and no error is shown in firebug console. Am I doing something wrong? Thanks, Laziale
I have a few guesses. The first one is probably wrong but I had to point it out. The code you posted does not have an end script (</script>) tag. You should check that first.
Second guess is, for some reason <%=FormView1.FindControl("chkMap").ClientID%> this might not be outputting the ID of that control. Have you tried to 'view source' of that page and made sure that the ID is as it should be? Maybe you've changed the ID of that checkbox or something.
Third guess is the way you reference the textbox (#textbox). This is an ASP.NET WebForms page. Your checkbox is a server control (<asp:CheckBox ... />). Are you sure you haven't created the textbox like <asp:TextBox runat="server" ID="textbox1" />? If you have, you would need to write the code like:
$('#<%=FormView1.FindControl("textbox1").ClientID%>').val($(this).is(':checked'));
to reference that textbox control via JavaScript.
I'm suggesting all these because the JS code works fine. I've created a JSFiddle and tested it.
Here's the fiddle. link

Call a javascript function from c# to replace a div

i have a web page in c#, in the codebehind i generate a url, on the aspx page i want to update an iframe to show this url.
after looking a while for the means to do this, i found i can register javascript to force the refresh of the iframe, but now i am experiencing a trouble.
no matter what i try, the url seems to never change, remaining at the on load defined url.
let me show you some of the code so you can see what i am doing and maybe help me with thi issue.
i have this string, who handles the url i want to go
public String currentMap = "google.com";
this is the function who registers the javascript
protected void Page_Load(object sender, EventArgs e)
{
UtilityClass utility = new UtilityClass();
this.Page.ClientScript.RegisterStartupScript(
this.GetType(),
"StartupScript",
"Sys.Application.add_load(MyLoad);",
true);}
this registers the javascript function, this function is suppoused to load a modified url, like this
<script type="text/javascript">
function MyLoad(sender) {
$get('maps').innerHTML += "<%= currentMap %>";
}</script>
while i can see how i the inner html updates (you can see i use the =+ operator, because i wanted to see if i was adding something to the page), but the value for currentMap is always the same, and the iframe does not gets updated.
i launch a function, when i click an object in a gridview, this function does something like this.
currentMap = "<iframe src=\"somepages.html" id=\"viewerframe\" width=\"100%\" height=\"450\"></iframe>"\"";
i can see the iframe updating, but the value remains at http://google.com (a test value hard coded).
how can i update the div so it shows the correct url in the iframe?
thank you for the help
To update the src of an iframe you can use this code:
//Set upload frame source
var uploadUrl = '/Profile/upload.aspx?id=' + $.url().param('id').replace('/', '');
$('#uploadFrame').prop('src', uploadUrl);

how to click a specific div and get information from it asp.net c#

I am making a table for schedule and putting div's on the table. People can make new appointments by clicking on one of the div .
I am changing the activeview when a div is clicked. I need to embed information in the div's so I can use it in the database and I want to know which div is clicked.
How can I solve this? Here is my code:
HtmlGenericControl div = new HtmlGenericControl("DIV");
div.Style.Add(HtmlTextWriterStyle.Width, "60px");
div.Style.Add(HtmlTextWriterStyle.MarginTop, "1px");
div.Style.Add(HtmlTextWriterStyle.BackgroundColor, "green");
div.Style.Add(HtmlTextWriterStyle.Height, last * 40 + "px");
div.Attributes.Add("onclick", "somefunction()");
div.Style.Add("cursor", "pointer");
bul.Controls.Add(div);
bul is a table cell where I put a DIV.
Don't forget to set an ID in your div server control
see this url which explains you how reference your server control in javascript:
http://encosia.com/2007/08/08/robust-aspnet-control-referencing-in-javascript/
Excerpt from article:
$get('<%= yourdiv.ClientID %>')
<script>
alert('yourdiv has a value of: ' + $get('<%= yourdiv.ClientID %>').value);
</script>
IMHO, you need to rethink about your approach.
I think you will need to seperate the solution into 3 different parts:
1- Server-side code: which will get the information about current appointments, and to save the new appointment that your audience may create.
2- Markup code: which should contain the basic building blocks for your markup, and not to generate everything from your server-side code, as #Senfo has suggested.
3- You should use some client-side code (Javascript) in order to switch between the normal-view mode, and the create-view mode.
4- if you don't want to use client-side code, you should decorate your div with 2 attributes in order to be able to deal with them in your C# code:
ID (which should be unique per every div)
Runat="Server" attribute
I know that my solution is not complete, but considering that this is a homework question, I think it's better to guide you to the correct path, but to let you move on according to these principles.
I think you can make it, and you should now create a much cleaner solution.
if you still can't figure it out, I will try to give you an example, but my advice is to take a deep breath, and start by your own :)
> .answer {
width:20px;
height:20px;
border-color:Red;
border:1px;
background-color:Green;
HtmlGenericControl div = new HtmlGenericControl("DIV");
div.ID = "testDiv";
div.Attributes.Add("class", "answer");
div.Attributes.Add("onclick", "somefunction(this)");
this.Controls.Add(div); // this code shlould be on pageload
<script language="javascript">
function somefunction(obj)
{
alert(obj.id);
}

how to refresh parent window by using Javascript in .cs

How to refresh the parent window while closing the popup window(child window).
We are calling the java script functions in code behind to refresh the parent window by using page.ClientScript.RegisterStartupScript().But t is working fine in IE(internet explorer) but not working in Mozilla Firefox and Google Chrome.
In the Mozilla Firefox the pop up value is saving in the database but it is not updating into the parent page.If i did refresh manually the value is getting updating into the parent page. If i put debugger in RefreshPage()(javascript function) function in IE it is firing but not in Firefox.
The below code for call the javascript function in .cs class.
page.ClientScript.RegisterStartupScript(this.GetType(), "PopupSave", "<script>javascript:alert('" + dsMessage.Tables[0].Rows[0]["ErrorMessage"].ToString() + "');window.open('','_self','');window.close();window.document.forms[0].submit();</script>");
The above code RefreshPage() is the javascript function to refresh the page
i.e.
function RefreshPage() { window.document.forms[0].submit(); }
Please help me i tried with different scenarios but no output.
instead of RefreshPage() i used different functions
like reload(),
window.opener.forms[0].submit(),
likewise but still no output anyone knows please help me.
Try this function
on submit button click run this script
<script language='javascript'> window.opener.frames.location='somepage.aspx';window.close();</script>
this will help you !!!
Before trying to make js calls between windows.
Set 'document.domain' to the same value on both pages.
protected void ButtonClick(object sender, EventArgs e)
{
string closeAndRefreshScript = #"<script type='text/javascript'>
window.opener.location.reload();
window.close();
</script>";
base.Response.Write(closeAndRefreshScript);
}

JQuery Facebox Plugin : Get it inside the form tag

I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want. The div that houses the facebox content is created outside of the tag so even though I am loading up some web controls none of them are firing back to the server.
Has anyone dealt with this that can give me some pointers?
poking around the facebox.js I came across this line in the function init(settings)...
$('body').append($.facebox.settings.faceboxHtml)
I changed that to ...
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
and it loads up in the form tag, not sure yet if there are any side effects
You can use this code to register the PostBack event:
btn.OnClientClick = string.Format("{0}; $.facebox.close();",ClientScript.GetPostBackEventReference(btn, null));
this will let the button fires a PostBack.
Even after the :
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
change I found it problematic. When you look at the page source using firebug you see that all the html in the div assigned to be the facebox div is doubled up (repeated).
So all of those controls with supposed unique id's are doubled up on the page, that can't be good on the postback, i've decided putting asp.net web controls in a facebox is not a good idea.
I modified facbox.js to do this. Maybe there is a better solution but this works like a charm
Here what i did:
add two lines on top of facbox.js before '(function($)'
var willremove = '';
var willremovehtml = '';
find "reveal: function(data, klass) {" and add this lines before the first line of function.
willremove = data.attr('id')
willremovehtml = $('#'+willremove).html()
$('#'+willremove).html('')
find "close: function() {" and make it look like below.
close: function() {
$(document).trigger('close.facebox')
$('#'+willremove).html(willremovehtml)
willremovehtml = ''
willremove = ''
return false
}

Categories