search

Home  >  Q&A  >  body text

javascript - Assign the obtained text element to var x; why can't it be judged whether the input text is empty?

Assign the obtained text element to var x; why does it not take effect to determine whether the input text is empty? document.getElementById("demo").innerHTML; Is the element obtained a string or something else? It is a string. Why does using x.length to determine the length of a string not work?

<style>
input {border:1px solid #ddd;}
</style>
<p>
<form>
<label>Please Enter nickname:</label><input type="text" name="fname" id="demo"><button onclick="infoBtn()">Submit information</button>
</form>
<script>
function infoBtn(){


   var x=document.getElementById("demo").innerHTML;
   if(x.length == 0 ||x==""){
       alert("输入不能为空");
       }else{
            alert("设置成功");
           }
   }

</script>
</p>

我想大声告诉你我想大声告诉你2771 days ago567

reply all(4)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-18 11:02:49

    First of all, I can't see whether your demo is input. If so, use val() instead of innerHTML. If not, you have to print out whether x can get the data.

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-18 11:02:49

    Why do we need to correct inputinnerHTML啊,用valueattributes?

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-18 11:02:49

    Use value and then add event listener

    reply
    0
  • PHPz

    PHPz2017-05-18 11:02:49

     var x=document.getElementById("demo");
       if(!x){
           alert("输入不能为空");
       } else {
           alert("设置成功", x.innerHTML);
       }
       

    reply
    0
  • Cancelreply