即使输入文本中没有文本也不会发出警报

时间:2020-07-11 12:05:30

标签: javascript

首先,如果我单击输入字段中没有文本的按钮,则会提示错误消息。但是如果我发送带有一些文本的消息,然后尝试发送空消息,则不会立即发出警报。

  const ip = document.getElementById('ip');
        const btn = document.getElementById('btn');
        
        const sm = document.getElementById('sm')
          btn.addEventListener('click' ,send);
        
          function send(e){
              if(ip.value===""){
                  alert("can't send empty message");
               
              }
              else{
              var k = ip.value;
              
              sm.innerHTML = k;
              ip.value = " ";
              
          }
          
        }
            <div class="container">
           <h1 id='msg'> Send Message for 
            free </h1>
            <input type="text" id='ip'>
            <button id="btn" type='button'>send</button>
            <h2 >sent message</h2>
            <h2 id='sm'> </h2>
        </div>

1 个答案:

答案 0 :(得分:1)

尝试以下更改:

 if(ip.value.trim()===""){
      alert("can't send empty message");              
  }