Daniel Scott Daniel Scott - 6 months ago 9
HTML Question

How to use JavaScript to test a HTML div on content from an external database?

I am trying to create a

html
letter. Each letter may or may not have conditions attached to it. Those conditions are stored in an
external sql database
.

What if a
html div
contained database field such as:-

<div id="Conditions">
<p>dbfield(var)</p>
</div>


What I need to do is test the resultant data rather than the actual
div
itself. See my last attempt:-

<div id="Conditions">
<p>dbfield(conditions)</p>
</div>

<div id="NoConditions">
<p>No specific conditions apply</p>
</div>

<script type="text/javascript" language="javascript">
<!--
if (document.getElementById("Conditions").innerHTML.length == 0){
document.getElementById("Conditions").style.display = "none";
document.getElementById("NoConditions").style.display = "inline";
}
else {
document.getElementById("NoConditions").style.display = "inline";
document.getElementById("Conditions").style.display = "none";
}
//-->
</script>


In a nutshell, my dilemma is I want to test whether a result is returned from the database or not.

I know this is a strange one but this is a
third party db
that I only have read access to inside a
web based interface
that creates the
html
form letters. However the prebuilt system has very limited functionality (can't use if's or then's) hence why I am using
javascript
to get around those limitations.

I'm assuming it is doing something tricky with the type of data in the
div
as I have tried NULL tests, "" tests,
innerHTML
tests, using a
i++ counter
,
children
tests,
haschildnode()
tests. So far it has resisted all my interrogations.

Any assistance would be appreciated.
Thanks

Answer

The conditions that you have put in your script is wrong. You have displayed the NoConditions div as inline in both if and else sections. Secondly, the length of innerHTML of Conditions div will always be greater than 0 since it has a p inside it everytime. So get the innerHTML of the p tag instead. Below is the snippet for the same. I hope this resolves your query.

var pText = document.getElementById("Conditions").getElementsByTagName('p')[0].innerHTML;
if (pText.length == 0){
        document.getElementById("Conditions").style.display = "none";
        document.getElementById("NoConditions").style.display = "inline";
    }
    else {
        document.getElementById("Conditions").style.display = "inline";   
        document.getElementById("NoConditions").style.display = "none";   
    }
<div id="Conditions">
    <p>Conditions</p>
</div>

<div id="NoConditions">
    <p>No specific conditions apply</p>
</div>