I've spent a while going through numerous similar questions, but based on the answers given, I'm lead to believe I have this setup correctly - but it's not working, and I'm not sure why.
I'm a newbie with Javascript/jQuery, so it's very possible (or probable!) that I'm missing something completely obvious here.
I have a page with a large 'main' div, and I'm loading content into that using jQuery .load via the navigation. That all works fine. However, some of the target pages are data-heavy, so I'm trying to integrate something in between to indicate to the user that the page is loading. Because there are numerous navigation elements, rather than having multiple functions (i.e one for each navigation element) I'm trying to do it in a single function, like so...
<script type="text/javascript">
function loadPage(pgurl) {
$('#main').html('<p align="center">Loading...</p>');
$('#main').load(' +pgurl+ ');
}
</script>
The problem I have is the onclick within the navigation. Prior to this, I had the .load within the onclick (i.e onclick="$('#main').load('/pages/testpage/');") and that worked fine. Now I'm firing the loadPage function via onclick, it's loading a black page (which firebug tells me is the site root).
Here's my onclick code;
<a onclick="loadPage('/pages/testpage/');return false;">Test</a>
I get no errors returned. I can only assume that the loadPage function is getting a zero value, rather than /pages/testpage/ - but I have no idea why!
Pointers much appreciated - much head scratching going on here!
It's already a string:
$('#main').load(pgurl);
$('#main').load(' +pgurl+ ');
needs to be
$('#main').load(pgurl);
You should probably write it as one line to prevent the second look up.
function loadPage (pgurl) {
$('#main').html('<p align="center">Loading...</p>').load(pgurl);
}
Is that a typo? Try changing:
$('#main').load(' +pgurl+ ');
to
$('#main').load(pgurl);
Because it seem you're not using the pgurl parameter, this thing in the load brackets is string a text of the variable name :)
$('#main').load(' +pgurl+ ');
use that instead
$('#main').load(pgurl);
Maybe you should look at that if you're not familiar with string concatenation http://www.youtube.com/watch?v=n17aX2TdQRk
You have to change following line // you pass string not a variable //
$('#main').load(' +pgurl+ ');
to
$('#main').load(pgurl);
Related
Good day! Newbie here. I just want to know if it's possible to change the whole content of an html using javascript? I got some codes here. (not mine but whoever did this, thank you so much!) I don't know where to put/insert all the codes of the new layout like when you click a button then the whole content will change. Thank you very much for helping me.
<script language="Javascript">
<!--
var newContent='<html><head><script language="Javascript">function Hi()</script></head><body onload="Hi();"><p id="p">hello</p></body></html>';
function ReplaceContent(NC) {
document.write(NC);
document.close();
}
function Hi() {
ReplaceContent(newContent);
}
-->
</script>
The easiest way to do this is with jQuery.
function insertHtml()
{
var newHtml = '<div><span>Hello World</span></div>';
$('body').html(newHtml);
}
Something like that will replace the entire contents of body with newHtml. You can also do this with pure javascript using the .innerHtml property but jQuery has many advantages.
EDIT: If you want to add something to the DOM rather than replacing the entire thing, use
$('body').append(newHtml)
instead. This will add the content to the end of the body. This is very often used for things like adding rows to a table.
Yes it is possible but this code is not valid unless you remove the comment tags however don't use the document.write() after page load unless you want to overwrite everything in page including the script
It could be a rookie mistake, but I've gone over my code enough times doing things such as; pre-pending .select-delete with div, attempted to use document.write("Hello") to see if the event was firing or not.
Here's a link to my jsFiddle: http://jsfiddle.net/gPF8X/5/
I really have no idea what's going on :(.
Any help would be greatly appreciated!
Edit: Linked to the incorrect JSFiddle, relinked to the correct one.
There is no - in your div class name.
<div id="1" class="selectdelete"></div>
$('.select-delete').click( function() {
Got it - id needs to be wrapped in quotes.
var value = $(this).attr('id');
The trigger is firing, but your code is not running because of an error - you're not quoting the string 'id' so it's an undefined value. Use your browser's debugger tool - it will help for this sort of thing.
Beyond that though, I can't say anything further because it's not clear what the desired result is.
Edit There's another issue as well - the selector is not working. You can't use the [ and ] character unquoted inside a jQuery comparison like that. The simplest solution is just not to have those characters in your input names. But you can also use escaping like so: $('select[name=g_country\\['+value+'\\]]').
I know you already accepted my other answer, but I just want to add for the record that there is another way to do it. Specifically, this seems like one of those cases where jQuery is less helpful rather than more. What I would do is change your HTML so the element names were also given as IDs, and then write it like so:
document.getElementById('g_country['+value+']').disabled = true;
document.getElementById('g_url['+value+']').disabled = true;
So, I see so many people wondering how to execute JS code returned via ajax. I wish I had that problem. My JS executes, but I don't want it too!
Using jQuery 1.4.2, I'm making a GET request:
$.ajax({
url:'/myurl/',
type:'GET',
success:function(response){
$('body').html(response);
}
});
The response looks something like:
<p>Some content</p>
<script>alert("hi!");</script>
Whenever the success callback fires and the response is injected into the DOM, the alert code fires! I don't want that to happen. What can I do to prevent this?
If you can't modify the response, try to "replace" <script> tags:
"<script>alert('hi');</script>".replace(/<(\/?script)/gi, "<$1");
This should escape the tags, making they appear as plain text instead of executing.
Related links
jQuery: Parse/Manipulate HTML without executing scripts
XSS Cheat Sheet
did you try returning function() snippets like
<script>
function Hello(){
alert('Hello');
}
</script>
This way the your JS doesn't execute right away but can be called later when required. But, again it depends what you actually want to do.
Depends. Do you need the JavaScript, or can you just get rid of it? If you don't need it at all, you could do something like
response = response.replace(/<script.*?<\/script>/gi, "");
However, if you need it, you're going to need to figure out how to kill just the function call(s) that you don't want. Using your example of an alert:
response = response.replace(/alert\(.*?\)/gi, "alert");
By getting rid of the trailing parens, and whatever they contain, you stop the function call from happening. Obviously, what you'll need in your regex will depend on the actual code that's causing the problem.
$('body').html(response.replace(/(<script)[^\>]*/g,'$1 src="emptyfile.js"'));
where emptyfile.js exists but has no content.
The problem you have is that jQuery strips script tags from the html and creates a document fragment.
To elaborate
var e = $("<div>Hello</div><script>alert('hi')</script>")
e.html(); // will not display script tags as script tags are now in a document fragment
$("body").append(e); // will execute the script tags in the fragment
See John Resig's explanation and another forum post on this topic.
So, what you can do is
var e = $("<div>Hello</div><script>alert('hi')</script>")
e.filter("script").each(function(){this.text='';});
That would basically make all the scripts empty and now you can
$("body").append(e);
See this post for the fragment creating routine.
I have the following DOM structure:
/*:DOC += <div id='testDiv' class='testDivClass'><div id='innerTestDiv'></div></div><span id='testSpan' class='testSpanClass'><span id='innerTestSpan'></span></span>
Now I tried to run jQuery select against them as follow. The first one returned alright, but the second one failed:
// works
var result = $('#testDiv')[0];
alert(result.id);
// failed: id is null or not an object
var result2 = $('#testSpan')[0];
alert(result2.id);
I tried selecting id instead of class and got the same results.
My question is: how can I get the second select to work? Is there some sort of invisible iterator/pointer in jQuery which I need to reset to the beginning of the DOM before the second select?
Thanks.
EDIT: Ok this is the official "does not work" version. testDiv matched, but testSpan did not, hence I got an error saying id is null or not an object error in the second alert.
UPDATE: I did a test by swapping testDiv and testSpan in the html. Now BOTH select failed.
UPDATE2: I have changed the html back to what it used to look like. I'm using JsTestDriver to write up the test, but it is actually not calling anything at the moment. The actual html looks messier than this (more nested tags). I'm trying to get this simplified version to work first. It appears that jQuery was able to get into the first select, whether it'll be span or div, but couldnt get out of it to do the second select. I've replaced jQuery.js and jsTestDriver.jar to no avail.
Thanks.
The .className selector matches by class, not ID.
Therefore, $(span.testSpan) won't match any elements.
You need to change it to $('span.testSpanClass') ot $(span#testSpan') (using the #id selector, which matches ID).
For more information, read the documentation.
I don't know why, but for me your code worked well.
I added $(document).ready(function() { before that code, and when I opened the test page, the alert box showed up perfectly, both of them! I don't know when do you want this alert box showed, but if it is when visitor open the page, just add that code. Otherwise, add
function objectid() {
var result = $('#testDiv')[0];
alert(result.id);
var result2 = $('#testSpan')[0];
alert(result2.id);
}
That code worked well for me, too.
PS: Sorry if you don't understand my bad english.
More than likely, there is something else wrong with the HTML you're actually using. Since you're posting only a tiny bit of the html, we can't actually test your problem. Post the entire page, or at least the smallest piece of it that actually has the problem when you run your test.
I tested the jQuery code you reported on JS Bin, and the code worked fine. As the code is very basic, I don't think the problem is caused by the version of jQuery used.
What I ended up doing is wrapping the entire html with a div or span tag. I found that jQuery could not get out of a div/span tag once it gets into one (in my above example), so I just make it to go into a div/span tag once.
Not sure whether this is a patch or ugly fix, but it solved my problem for now.
Thanks for all the help!
Use "#" to select by id, use "." to select by class...
Firstly, is there a way to use document.write() inside of JQuery's $(document).ready() method? If there is, please clue me in because that will resolve my issue.
Otherwise, I have someone's code that I'm supposed to make work with mine. The catch is that I am not allowed to alter his code in any way. The part that doesn't work looks something like this:
document.write('<script src=\"http://myurl.com/page.aspx?id=1\"></script>');
The script tag is referencing an aspx page that does a series of tests and then spits out something like so:
document.write('<img src=\"/image/1.jpg\" alt=\"Second image for id 1\">')
The scripts are just examples of what is actually going on. The problem here is that I've got a document.write() in the initial script and a document.write() in the script that get's appended to the first script and I've got to somehow make this work within JQuery's $(document).ready() function, without changing his code.
I have no idea what to do. Help?
With the requirements given, no, you can't use document.write without really hosing up the document. If you're really bent on not changing the code, you can override the functionality of document.write() like so and tack on the result later:
var phbRequirement = "";
$(function() {
document.write = function(evil) {
phbRequirement += evil;
}
document.write("Haha, you can't change my code!");
$('body').append(phbRequirement);
});
Make sure you overwrite the document.write function before it is used. You can do it at anytime.
The other answers are boring, this is fun, but very pretty much doing it the wrong way for the sake of fulfilling the requirements given.
picardo has the approach I would've used. To expand on the concept, take a read:
$('<script/>')
.attr('src', 'http://myurl.com/page.aspx?id=1')
.appendTo('body');
Alternate style:
var imgnode = $('<img alt="Second image for id 1"/>')
.attr('src', "image1.jpg");
$('#id1').append(imgnode);
Be sure to use the attr method to set any dynamic attributes. No need to escape special symbols that way.
Also, I'm not sure what the effectiveness of dynamically generating script tags; I never tried it. Though, it's expected that they contain or reference client-side script. My assumption is that what page.aspx will return. Your question is a little vague about what you're trying to do there.
jQuery has a ready substitute for document.write. All you need to use is the append method.
jQuery('<img src=""/>').appendTo('body');
This is fairly self-evident. But briefly, you can replace the with whatever html you want. And the tag name in the appendTo method is the name of the tag you want to append your html to. That's it.
picardo's answer works, but this is more intuitive for me:
$("body").append('<img src=\"/image/1.jpg\" alt=\"Second image for id 1\">');
Also, for the script part that is being inserted with document.write(), check out jQuery's getScript() function