Reputation: 1797
So I have a problem here. I have set some custom styles for a few divs to make them temporarily invisible. However these custom styles does not seem to trigger when I generate text from an outside .js file with the document write function:
CSS:
<style type="text/css">
.section
{
display: none;
}
.section#form1
{
display: block;
}
JavaScript function to toggle visibility:
function toggleVisibility(newSection)
{
$(".section").not("#" + newSection).hide();
$("#" + newSection).show();
}
Somewhere inside my recursive loop function that generates most of the content on this page I have this
...
if (step != 1)
{
document.write("</div>");
}
document.write("<div id='form"+step+"' class='section'>");
...
Do I need some sort of code to assign where JavaScript prints out all the elements of my form to a certain outer div? I can't seem to understand why all the divs are visible at the beginning, I did the same code earlier and it worked just fine then. Perhaps a good alternative to document.write might do the trick. Feels like document.write sorta overrides everything.
$(document).ready(function()
{
$('#show-results').click(function()
{
$.post('JSAAN.php', function(data)
{
var pushedData = jQuery.parseJSON(data);
// Uses the function from loop.js
document.write("<form id='evalForm' onsubmit='return false;'>");
var fieldsetActive = 0;
loop(pushedData);
})
})
});
And the loop function (who's in a separate file starts like this:
function loop(obj) {
// Starts the form
$.each(obj, function(key, val) {
if($.isPlainObject(val) || $.isArray(val)) { // object, call recursively
Upvotes: 0
Views: 692
Reputation: 6030
because when you use document.write
it overwrites everything in the page including styles etc, I think you should consider using DOM functions instead of using document.write
Upvotes: 0
Reputation: 227200
You shouldn't be using document.write
. If the page is fully loaded, it will erase the entire page (including the CSS).
You seem to be using jQuery already, so use its .append
or .html
methods instead.
Upvotes: 2
Reputation: 2751
Instead of using document.write
to create your div
, consider using document.createElement
.
var elem = document.createElement('div'),
formStep = 'form' + step;
elem.setAttribute('id', formStep);
elem.setAttribute('class', 'section');
This will insert the element into the DOM. document.write
is not recommended for this type of usage.
If you need to use jQuery:
// using document.createElements('div') as the selector is the fastest way
var elem = $(document.createElement('div')),
formStep = 'form' + step;
elem.attr('id', formStep).attr('class', 'section');
Let me know if you have any questions.
Upvotes: 3