开发者

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.getElem开发者_C百科entById('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


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


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>


You may try this:

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


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);


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜