如果在文本框中没有输入文本,则阻止按钮向div发送文本 - Javascript

时间:2016-04-09 19:16:09

标签: javascript

我没有使用表单但有文本区域。我想确保如果文本区域为空并且按下发送消息的按钮,则无法发送空白消息。

2 个答案:

答案 0 :(得分:0)

你有与此相关的代码吗?您只需要检查<textarea>的剪裁长度,看看是否有任何内容,然后发送您的消息:

if(!message || message.value.trim().length === 0){
      alert('A message is required.')
}
else{
      // Send your message
}

完整的示例可能如下所示:

<textarea id='check-me'></textarea>
<br />
<button onclick='sendMessage();'>Send Message</button>
<script>
function sendMessage(){
  // Get your textarea and check it's content
  var message = document.getElementById('check-me');
  // Check the message
  if(!message || message.value.trim().length === 0){
      alert('A message is required.')
  }
  else{
      // Send your message
  }
}
</script>

答案 1 :(得分:0)

您只需在sendText功能中添加空值检查:

function sendText() {
    var textValue = document.getElementById('post_box').value;

    if (!textValue || textValue.length === 0) {
        return;
    }

    ...
}

return语句将使您的函数不再执行,因为对于空textValue,检查不会成功。在这种情况下,您可以向用户显示一条消息,说明文本字段为空。