表单提交添加点击事件,并判断内容是否为空
最近刚好在做到个人博客发表博客部分,包括标题、分类以及内容三个部分。通过form表单提交,这里只做相对简单的处理,提交的时候需要判断输入内容是否为空,如果为空或者全部是空格,则不让提交。具体实现如下:
<!--表单部分-->
<form action="/blog/addBlog" method="post" name="blog">
<input type="text" name="title" class="title_blog" placeholder="请输入文章标题"/><br>
<input type="text" name="type" class="type_blog" placeholder="请输入文章分类"/><br>
<textarea name="content" onkeyup="convert()" placeholder="请输入内容"> </textarea>
<input onclick="return notNull()" value="发表"/>
</form>
//点击事件函数
//标题、分类、内容不能为空
<script type="text/javascript">
function notNull() {
if (document.blog.title.value.toString().trim().length <= 0 ||
document.blog.type.value.toString().trim().length <= 0 ||
document.blog.content.value.toString().trim().length <= 0) {
alert("输入内容不能为空!");
return false;
}else {
return true;
}
}
</script>
简单说明:通过document.blog.title.value获取相应的输入框内容,然后将其转化为字符串,通过字符串的.trim()方法,判断是否为空以及全部是空格。
.tirm()的作用是去掉字符串的首尾全部连续的空格,如果剩下的长度小于等于0,这说明全部是空格或者本身就为空。