Update Javascript function content on postback - javascript

Here's my code
<script type="text/javascript">
function getNextScroll(i){
<asp:Literal ID="infiniteScrollTableJS" runat="server"></asp:Literal>
}
</script>
I am populating that Literal with some Javascript from the CodeBehind. This works great OnLoad. However, when I do a postback I have a problem. The Literal is updated on postback. The actual script that is inside the function actually gets changed (I can see it with Firebug). BUT, the function is unaware that there is new script in there, it just keeps running the old stuff.
So near as I can tell, I want to 're-initialize' the code inside the function after postback.
I know how to call a function after postback using add_endRequest.
This problem is not unique to .NET or anything. In fact, I have a simple example here -> http://jsfiddle.net/7JxY7/1/ 'Run Function' will always alert 'one' even after the script contents are changed.
I feel like jQuery probably has something that I could use, but searching around I have found nothing.
EDIT:
I tried the suggestion by mblase75. This works great in Javascript ( more importantly, now I understand why) , however, given this approach, I still can't get it working with the postback. Here is my updated code.
<script type="text/javascript">
function getNextScroll(i){
//some stuff
}
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function (s, e) {
//mblase75 suggestion
getNextScroll = function (i){<asp:Literal ID="infiniteScrollTableJS" runat="server"></asp:Literal>};
});
</script>
I thought this would work, but of course, it has the same problem as my original method. The Literal is actually changed, but the function doesn't know about the change, it still has the original code

In JavaScript, a function is actually an object. So instead of trying to rewrite the <script> element with a string, replace the function (variable) name with a new function object:
<script>
goTest = function(){
alert('one');
}
function changeTest1(){
goTest = function(){alert('two');};
alert('ok');
}
</script>
<a onclick="goTest();">Run Function</a><br/>
<a onclick="changeTest1();">Change Function</a>
​
http://jsfiddle.net/7JxY7/2/

Related

Basic HTML JavaScript function not working as intended

I'm wandering if anyone can help. Im doing some rather basic JS for a project but I'm an idiot and not sure how to do this element.
I've used an opensource word highlighting program i've found online which works when i input a string to be highlighted, but when i input "input_id.value" which is a working (tested) value of an input box, The highlighter doesnt work. I thought it could be that it's not updating i.e it only runs once so it will try to highlight no value as nothing has been inputted.
This is the code snippet:
<script type="text/javascript" src="../Resources/hilitor.js"></script>
<script type="text/javascript">
var input = document.getElementById("input_id").value;
// global variable
var myHilitor;
document.addEventListener("DOMContentLoaded", function() {
myHilitor = new Hilitor();
myHilitor.apply("fox");
}, false);
</script>
This works correctly and higlights "fox" as shown in this image.
However when i change
myHilitor.apply("fox");
to
myHilitor.apply(input_id.value);
nothing is highlighted at all. I tried putting the whole thing into a function like an idiot but that also doesnt work
<script type="text/javascript" src="../Resources/hilitor.js"></script>
<script type="text/javascript">
function searchFunction(){
var input = document.getElementById("input_id").value;
// global variable
var myHilitor;
document.addEventListener("DOMContentLoaded", function() {
myHilitor = new Hilitor();
myHilitor.apply("fox");
}, false);
}
</script>
The function is called by
<button onclick="searchFunction()" class="button"></button>
I'm truly dumbfounded, any help would be very appreciated. Thankyou :)
Thanks all for the helpful contributions, Problem is solved I'm waiting to be able to accept answer
document.addEventListener("DOMContentLoaded", function() { causes a function to run when the DOMContentLoaded event happens (which is about when </html> is parsed as the document loads).
You haven't shown how searchFunction is called, but odds are that it is when a button is clicked.
That will happen after the DOMContentLoaded event has occurred so the condition for the function running never happens.
Don't include that condition.
Your variable is called var input but you're using input_id here myHilitor.apply(input_id.value) ;
You have declared var input = document.getElementById("input_id").value;.
But while calling myHilitor.apply(input_id.value); you are passing input_id.value. You should pass just input.
Like myHilitor.apply(input);

Function with arguements inside jQuery

Can someone please help why this is not working.
HTML Code:
<li><a href="#" onclick="adminDBDisplay(ownorg);" >OOrg</a></li>
<li><a href="#" onclick="adminDBDisplay(twoorg);" >Twoorg</a></li>
jQuery:
$(document).ready(function(){
function adminDBDisplay(db){
alert("Got into function" +db);
// Planning to use jQuery Ajax here
}
});
When I look using Firebug, I get following error:
"ReferenceError: adminDBDisplay is not defined"
Can someone please help me why this is not working. There something wrong on how I am approaching this. Please let me know if there are better ways. Thanks for your help.
When defining a function with function name() {...}, if you are already inside a function, then it will only be defined in that function.
Function definitions should not be wrapped in a .ready(), since they don't run until they are called. Remove the .ready() wrapper and you should be good to go.
The following notation:
$(function() { ... });
itself is a function that binds function() {...} to document.ready. And running function adminDBDisplay(db){...} in document.ready only defines the function it at runtime, but doesn't actually call it. In order to call it, you would want adminDBDisplay('parameter');
To effectively implement it, you'll want to place it within the body of your page as follows:
<head>
<script src="yourversionofjquery.js"></script>
<script>
//Defining your function for calling later
function adminDBDisplay(db)
{
alert("Got into function" +db);
//Planning to use Jquery Ajax here
}
</script>
</head>
<body>
<script>
//Binding an anonymous function to document.ready
$(function () {
//Do whatever you want after document.ready
});
</script>
<div> rest of body</div>
</body>
Let me know if that makes sense/fixes your errors.
EDIT: also, put 'single quote' around 'ownorg', like "adminDBDisplay('ownorg');" otherwise it's looking for a variable called ownorg.

Click button on load event

I have the following javascript -
function onLoad() {
if (!(document.applets && document.VLVChart && document.VLVChart.isActive())) {
setTimeout('onLoad()', 200);
return;
}
objChart = document.VLVChart;
PollEvent();
}
function fan() {
objChart.reorganize();
}
And then when the HTML page is loaded -
<body onLoad="onLoad()">
and have a button within the HTML that execute the fan() function -
<input type='button' value='Fan' onClick='fan();'>
Is it possible for me to activate the fan() function within the onload event so that a user does ont have to click the button?
EDIT
After trying the provided answers, on debugging the code breaks on the line -
objChart.reorganize();
Within the fan() function with the error -
SCRIPT5007: Unable to get value of the property 'reorganize': object is null or undefined
This is odd as when I manually click the button on the page, the function works fine.
Solution
After much head scratching I have realised that I was trying to load the fan() function before the page (and more specifically the objChart) had fully loaded. Hence why adding the function in the onLoad event was not working. I added a setTimeout -
function Fan()
{
setTimeout(function(){objChart.reorganize();},3000);
}
<body onload='onLoad(); fan();'>...
However inline JS is best avoided and you would do well to begin looking into centralised event management. There are various advantages to this.
An answer I wrote yesterday to another question outlines why this is. Something like jQuery makes this trivial if it's new for you.
$(function() {
$('body').on('load', function() {
onLoad();
fan();
});
});
Reading your question I assume you didn't even have tried. Just call that function from within your onLoad()-function:
function onLoad()
{
fan();
/* … */
}
Yes.
You can use <body onload='onLoad(); fan();'> as Utkanos suggests.
If you use jQuery, you can also stick a script in the head containing:
$(function(){
...
});
The jQuery function actually fires earlier, as is explained here.

JQM .bind function call hangs on a method, but script still completes

I'm just getting started with Javascript, jQuery, and jQuery Mobile. I'm trying to go through a tutorial online, but I'm getting caught up on the mobileinit event handler. Here is the code:
<script type="text/javascript">
$(document).bind("mobileinit", function() {
Notes.testHelper.createDumyNotes();
Notes.controller.init();
});
</script>
If I put an alert before and right after Notes.testHelper.createDummyNotes(); the alert is called. However, if I put the alert right after Notes.controller.init(), the alert isn't called. I imagine this means the code stopped in that function. However, if I put an alert right before the closing script tag outside of the function, that alert is called--This is what confuses me. How can a method hang and not allow the rest of a function to complete but still let the script complete?
As an interesting aside, I forgot to put the script tags around this .bind function at first, and the html was styled correctly. However, once I put the tags around this function, the html appeared but wasn't styled.
Any suggestions? As I said, I'm new to javascript, so this could be a fundamental misunderstanding of the way the language executes.
Thanks for your help!
The contents of $(document).bind("mobileinit", function() { ... } will be called when the mobileinit event is triggered, which will be AFTER the code between the script tags are read. This is why the alert you placed just before the closing script tag is executed.
If you put alert(1); before the closing tag, and alert(2); after the function() { and alert(3) after the createDumyNotes(), you will probably get 1 and 2 but not 3.
I think you're on the right path in that the error is occurring in the createDumyNotes() function. I suggest you get into that function with some try { ... } catch(e) { ... } and pinpoint where the error is occurring (assuming Notes and Notes.testHelper are valid objects, and Notes.testHelper.createDumyNotes() is an existing function.
EDIT
I just noticed that your function is createDumyNotes() instead of createDummyNotes(). Is this nothing more than a misspelling?

Onclick in <a> cause reloading of the page insted of executing JS code

My URL: http://www.example.com/?product=3&url=XYZ
My code:
link
After click, page is reloading, instead of executing foo() function.
JS is enabled. Body of foo():
function foo() { alert("sss"); }
Probably, this problem is caused by URL of my site. XYZ parameter is a url of a website but with something like "%C5%82%C3%B3" instead of special characters (something like after using htmlspecialchars()).
What is interesting, after click the page is reloaded with the "normal" URL, something like: http://www.example.com/?product=3&url=http://www.example.com (WITH special characters like " / ").
What can I do to resolve this problem?
EDIT
Above code works fine. Thank you for your time.
Yeah, there's definitely something else going on here. Here's a minimal example that works just fine:
<html>
<body>
link
<script type="text/javascript">
function foo() { alert("hi"); }
</script>
</body>
</html>
Assigning onclick inline is not a good practice, and you should be doing something like
<a id="someId" /* ... */ >
// ...
<script type="text/javascript">
function foo() { alert("hi"); return false; }
document.getElementById("someId").onclick = foo;
</script>
but in any case, the most likely culprit is that your script has a syntax error somewhere and is not loading at all. You can verify this by setting onclick="return false". If that doesn't work, it's likely you have some other event handler that's being triggered. But because the above -- all we know of your code -- works, it's unlikely anyone here can diagnose what the problem is without more information.
Edit
Nevermind this, I fully assumed your code wasn't working and the below did. But I guess the code you posted was already correct.
On a seperate note, you should avoid using attributes like onClick, create event handlers instead (I suggest looking at jQuery).
i tried the same code in my systm.the code is workin and the alert box is visible.
My code:
<a href="#" onclick="foo();return false;">link/a>
and javascript is
<script type="text/javascript">
function foo()
{
alert("sss");
}
</script>
i am using vs2008

Categories