How to call script jquery when web page is showned? - javascript

my process is when user click button print in first form then process is redirect to second page. Now when second page is showed i want to call jquery .How can i do , Please help. because i want to get html from second page.
this is my code in web
<script>
$(function () {
setTimeout(function () { printForm() }, 3500);
function printForm() {
window.onload(function () {
<%testMethod();%>
});
}
});
</script>
this is my code in code behide
public void testMethod() {
if (!Page.IsPostBack)
{
WebClient MyWebClient = new WebClient();
string html = MyWebClient.DownloadString(Session["url"].ToString());
}
}
But the problem is testMethod is calling before scond page is show. i want to do like window.print()

If I understand you correctly, you want to get jquery when other page loads, to do that with js only, you have to do something like this:
your_server ="some_server_name"
(function() {
var jquery_scrpt = document.createElement('script'); jquery_scrpt.type = 'text/javascript'; jquery_scrpt.async = true;
jquery_scrpt.src = 'https://' + your_server + '//code.jquery.com/jquery-1.11.2.min.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(jquery_scrpt);
})();
this will add jquery dynamically to your page.Hope that helps.

Related

Calling a jquery function in code using vb.net

having a bit of an odd problem, the situation is a bit unique in that I want to show/hide a div in instances both server side and client side, as such I cant change it to a panel.
The current code I have to change its visiblity client side, which works, is:
$('#<%= txtSurname.ClientID%>').on('input', function hideControl() {
var current = $('#<%= txtSurname.ClientID%>').val();
var surname = $('#<%= hdnSurname.ClientID%>').val();
if (current == surname) {
$('#pnlReason').hide()
console.log('hiding');
} else {
$('#pnlReason').show()
console.log('showing');
}
});
When a user clicks a button, the page validates, and refreshes, and the panel is rendered invisible again. As such I want to run this code again on the page load so that if the two variables are still different when the page validation is run, the panel is still visible. This is what im using to call it serverside:
Page.ClientScript.RegisterStartupScript(Page.GetType(), "ShowHide",
"$(document.ready(hideControl()));", True)
When I try running it however, it says that hideControl is undefined, any ideas whats going wrong?
you could reorganise your jquery like this and once the page is refreshed, you can execute your function at the end of the document ready without the need for RegisterStartupScript():
//shorthand for document.ready
$(function () {
var hideControl = function() {
var current = $('#<%= txtSurname.ClientID%>').val();
var surname = $('#<%= hdnSurname.ClientID%>').val();
if (current == surname) {
$('#pnlReason').hide()
console.log('hiding');
} else {
$('#pnlReason').show()
console.log('showing');
}
}
$('#<%= txtSurname.ClientID%>').on('input', function () {
hideControl();
});
//call it at end of ready function:
hideControl();
};
Since hideControl is defined as anonynous function you can't access it. You have to define the function hideControl outside of the on event handler. Put the function within the script tags in the page not in a separate file:
<script>
function hideControl() {
var current = $('#<%= txtSurname.ClientID%>').val();
var surname = $('#<%= hdnSurname.ClientID%>').val();
if (current == surname) {
$('#pnlReason').hide()
console.log('hiding');
} else {
$('#pnlReason').show()
console.log('showing');
}
}
</script>
Then call the function like that at server side without the parenthesis:
Page.ClientScript.RegisterStartupScript(Page.GetType(), "ShowHide",
"$(document.ready(hideControl));", True)

Javascript not working when 'alert; is removed

I have the following JS on my html and my obervations are:
1) When I removed the line for "alert" display it is not working as expected, the SAVE button is not trigerring when clicked.
2) Even with the "alert", it is not working in CHROME.
function save() {
alert('View Full List triggered!');
var $form = $('.fancybox-inner').find('[data-area="funder-detail"]');
$form.on('click', '[data-action="save-funder"]', function () {
var selected1 = $form.find('input[type="radio"]:checked').val();
if ($('input[type="radio"]:checked').length == 0) {
parent.$.fancybox.close();
} else {
document.getElementById("txtFunder").value = selected1;
parent.$.fancybox.close();
}
});
}
Perhaps the script runs too early, when the form is not yet in the DOM?
This can happen when the script tag is in the header.
Try moving the script tag in front of the closing tag.
I was able to make it work by using onclick="setTimeout(save, 1000)"

Reload the page using sammy.js

I am using sammy.js for single page application in asp.net mvc. Everything is fine, but I am facing one problem which is that I can not reload the page. For example When I am in the dashboard my URL is
http://localhost:1834/#/Home/Index?lblbreadcum=Dashboard
layout.cshtml
<script>
$(function () {
var routing = new Routing('#Url.Content("~/")', '#page', 'welcome');
routing.init();
});
</script>
routing.js
var Routing = function (appRoot, contentSelector, defaultRoute) {
function getUrlFromHash(hash) {
var url = hash.replace('#/', '');
if (url === appRoot)
url = defaultRoute;
return url;
}
return {
init: function () {
Sammy(contentSelector, function () {
this.get(/\#\/(.*)/, function (context) {
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
}).run('#/');
}
};
}
I want to reload the page by clicking the dashboard menu/link. But click event not firing because link is not changing. But if I want to go another page then it is fine. Please help me out. Thanks.
I think you have to append the same partial again. You can't "update" the partial in that meaning.
As you say in your post, when you click another link and then back again it works.
That's what you'll have to do. Append the same page/partial again, by doing that you clear all variables and recreate them, by that simulating a refresh.
EDIT: Added example
Observe that I didn't copy your code straight off but I think you'll understand :)
And I don't use hash (#) in my example.
var app = Sammy(function () {
this.get('/', function (context) {
// context is equalient to data.app in the custom bind example
// currentComponent('home'); I use components in my code but you should be able to swith to your implementation
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
this.bind('mycustom-trigger', function (e, data) {
this.redirect('/'); // force redirect
});
this.get('/about', function (evt) {
// currentComponent('about'); I use components in my code but you should be able to swith to your implementation
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
}).run();
// I did an easy example trigger here but I think you will need a trigger on your link-element. Mayby with a conditional check wheter or not to trigger the manually binding or not
$('.navbar-collapse').click(function () {
app.trigger('mycustom-trigger', app);
});
Please read more about events and routing in sammy.js
Good luck :)
An easier and cleaner way to force the route to reload is to call the Sammy.Application refresh() method:
import { sammyApp } from '../mySammyApp';
const url = `${mySearchRoute}/${encodeURIComponent(this.state.searchText)}`;
if (window.location.hash === url) {
sammyApp.refresh();
else {
window.location.hash = url;
}

How to add javascript file dynamically in the head of html?

From below code I am trying to load javascript file TestJScript.js dynamically and after loading want to call javascript function LoadData() exist in that file. But I am getting error please check image.
Note: Error get only on IE-8.0.6001 update 0.
Please suggest me correction such that It will work from 6 to all version of IE.
Or any another solution.
if it require any windows updates. Please let me know.
Please don't suggest with JQUERY code
Javascript file code :
function LoadData() {
alert('ok');
}
Code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function LoadJSFile() {
var js = document.createElement("script")
js.setAttribute("type", "text/javascript")
js.setAttribute("src", "C:\\TestJScript.js")
document.getElementsByTagName("head")[0].appendChild(js)
//call below function exist in TestJScript.js file
LoadData();
}
</script>
</head>
<body onload="LoadJSFile();">
</body>
</html>
Error Image:
Try this http://dustindiaz.com/scriptjs.
Like this:
$script('yui-base.js', function() {
// do stuff with base...
$script(['yui-anim.js', 'yui-connect.js'], function() {
// do stuff with anim and connect...
});
$script('yui-drag.js', function() {
// do stuff with drag...
});
});
The error reports a problem in the javascript file that you're loading. So the problem lies not in how you dynamically load the javascript file, but in the javascript file itself.
It looks like there is a problem with the file once it has loaded. Are you sure there is no syntax error in the file itself.
Also, I would recommend you use a relative path to the javascript file instead of the absolute path.
EDIT:
Try this:
function LoadJSFile() {
var script = document.createElement('script');
script.src = "C:\\TestJScript.js";
script.onload = function () {
LoadData();
};
document.getElementsByTagName("head")[0].appendChild(script)
}
You could try the following:
<script>
function LoadJSFile(src, callback) {
var js = document.createElement('script');
js.src = src;
js.async = true;
js.onreadystatechange = js.onload = function() {
var state = js.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(js);
}
LoadJSFile('C:\\TestJScript.js', function() {
LoadData();
});
</script>
If you are using c# code then another solution to solve this script error is, invoke script through c# code.
Code:
/
/Assiging html value to control
webBrowser.DocumentText = "HTML content";
//Calling document load completed event
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlDocument htmlDocument = webBrowser.Document;
HtmlElement htmlElementHead = htmlDocument.GetElementsByTagName("head")[0];
HtmlElement HtmlElementScript = htmlDocument.CreateElement("script");
HtmlElementScript.SetAttribute("text", "C:\\TestJScript.js");
htmlElementHead.AppendChild(HtmlElementScript);
htmlDocument.InvokeScript("LoadData");
webBrowser.DocumentCompleted -= webBrowser_DocumentCompleted;
}

incrementing a value after each refresh in javascript

I'm developing a web application in asp.net c#, which has a URL like this...
http://localhost:1096/DisplayPop3Email.aspx?emailId=10
After a given time, I want to refresh the page, increasing the value of emailId. This is a repeating process that should happen after a certain amount of time has passed.
After the first refresh, the URL should now look like this...
http://localhost:1096/DisplayPop3Email.aspx?emailId=11
I have written a javascript function to refresh the page after a fixed time, but how can i increase the value of emailid after each refresh?
This is my Javascript code...
<script type="text/javascript">
var sURL = unescape(window.location.pathname);
function doLoad(){
setTimeout("refresh()", 2*15000 );
}
function refresh(){
window.location.href = sURL;
}
</script>
<script type="text/javascript">
function refresh() {
window.location.replace( sURL );
}
</script>
I call doload() from inside another Javascript function, as per below...
<script type="text/javascript">
function openNewWindow(spcd,cval) {
var tt = spcd;
var testarray=(spcd).split('#%#');
for(i=0;i<testarray.length-1;i++) {
var theurl=testarray[i];
if(theurl=="http://www.colbridge.com"){
popupWin = window.open(theurl,'_blank','menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0')
break;
}
}
receiveval(cval);
doLoad();
}
</script>
I call openNewWindow(spcd) inside my asp.net page_load event.
Could someone please help me to identify how to increment the counter after each refresh.
Call the function below:
function goToNextId() {
var id = 1 + parseInt(window.location.href.match(/emailId=(\d+)/)[1]);
window.location.href = window.location.href.replace(/emailId=(\d+)/, "emailId=" + id);
}

Categories