Lion King
Lion King

Reputation: 33813

Error: my variable is null

I have an error in my simple javascript code.

HTML

<input type="text" name="txt" id="txt" value="Hello" />

JavaScript

<script type="text/javascript">
 var txt = document.getElementById('txt').value;
 var txt2 = (null == document.getElementById('txt2').value)? "" : document.getElementById('txt2').value;
 alert(txt2);
</script>

I know that the element called txt2 does not exist, but I want that if an element does not exist variable txt2 will be assigned a default value

Upvotes: 0

Views: 2114

Answers (5)

Matt Ball
Matt Ball

Reputation: 359776

You only need to check the truthiness of the value returned by document.getElementById().

var txt = document.getElementById('txt').value,
    txt2_element = document.getElementById('txt2'),
    txt2 = txt2_element ? '' : txt2_element.value;

alert(txt2);

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You may try this:

var txt2Element = document.getElementById('txt2');
var txt2 = (txt2Element != null) ? txt2Element.value : '';

Upvotes: 1

GoatInTheMachine
GoatInTheMachine

Reputation: 3773

You where comparing null against the value of txt2, which doesn't exist. This might work...

<script type="text/javascript">
  var txt = document.getElementById('txt').value; 
  var txt2 = (null == document.getElementById('txt2')) ? "" : document.getElementById('txt2').value;
  alert(txt2);
</script>

Upvotes: 1

Jon Gauthier
Jon Gauthier

Reputation: 25572

Instead of checking if the value is null, just check if the element is null:

var txt2 = ( document.getElementById('txt2') === null )? "" : document.getElementById('txt2').value;

Upvotes: 0

Town
Town

Reputation: 14906

var txt2 = document.getElementById('txt2') ? document.getElementById('txt2').value : "";

Upvotes: 2

Related Questions