开发者

Error: my variable is null

开发者 https://www.devze.com 2023-02-18 14:24 出处:网络
I have an error in my simple javascript code. HTML <input type=\"text\" name=\"txt\" id=\"txt\" value=\"Hello\" />

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

精彩评论

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