user1451890
user1451890

Reputation: 1095

Dynamically Writing Vars to a Webpage

I have the following function below and it works great when all 3 vars are not null, however, how can it be modified such that when either variable (tel, fax, cell) are null, that the line containing the null variable does not get written?

Current scenario:
T. 123-4567-8910
F. 987-654-3210
C. 
-------------------------------
Desired scenario:
T. 123-4567-8910
F. 987-654-3210
-------------------------------
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function test() {

var tel = "123-4567-8910"
var fax = "987-654-3210"
var cell = ""

var html =
        '<div>T. '+ tel +'</div>\n' +
        '<div>F. '+ fax +'</div>\n' +
        '<div>C. '+ cell +'</div>'

document.write(html)

}
</script>
</head>
<body>
<a href="javascript:test()">test</a>
</body>
</html>

Upvotes: 0

Views: 64

Answers (3)

crashwap
crashwap

Reputation: 3062

Try this:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function test() {
            var tel = "123-4567-8910";
            var fax = "987-654-3210";
            var cell = "";

            var html = "";

            if (tel == "") {
                html = html + '<div>T. '+ tel +'</div>\n';
            }
            if (fax == "") {
                html =  html + '<div>F. '+ fax +'</div>\n';
            }
            if (cel == "") {
                html = html + '<div>C. '+ cel +'</div>\n';
            }
            document.append(html);
        }
    </script>
</head>
<body>
<a href="javascript:test()">test</a>
</body>
</html>

Upvotes: 0

Christophe
Christophe

Reputation: 28134

You need to test each variable:

var html =
    ((tel)?'<div>T. '+ tel +'</div>\n':'') +
    ((fax)?'<div>F. '+ fax +'</div>\n':'') +
    ((cell)?'<div>C. '+ cell +'</div>':'') ;
document.write(html);

How it works:

(tel)?'<div>T. '+ tel +'</div>\n':''

means: if tel is not empty/null then '<div>T. '+ tel +'</div>\n' else ''

Demo: http://jsfiddle.net/gHdy8/

Upvotes: 0

Jivings
Jivings

Reputation: 23250

Let me introduce you to conditional statements:

var html = '';
if (tel) {
  html += '<div>T. '+ tel +'</div>\n';
}
if (fax) {
  html += '<div>F. '+ fax +'</div>\n';
}
if (cell) {
  html += '<div>C. '+ cell +'</div>\n';
}
document.write(html)

Although document.write() is usually considered a bad idea. You can read more about it here.

Upvotes: 1

Related Questions