在js中返回false不起作用

时间:2015-08-26 11:48:07

标签: javascript php jquery

我知道这个问题已经被多次提出过,但我很难理解为什么<form name="MyForm" method="post" action=""> <div class="span-5"> <label>Select Class</label> <div> <select name="selectclass" id="selectclass"> <option value="none">-Select Class-</option> <?php while($class=mysqli_fetch_array($fetchclass)) { ?> <option value="<?php echo $class['class_name'];?>" <?php if(isset($_POST['selectclass'])) { if(!strcmp($_POST['selectclass'],$class['class_name'])) echo "selected"; }?> ><?php echo $class['class_name'];?></option> <?php }?> </select> </div> </div> <div class="span-5"> <label>Select View</label> <div> <select name="selectview" id="selectview"> <option value="none">-Select-</option> <option value="chapter" <?php if(isset($_POST['selectview'])) { if(!strcmp($_POST['selectview'],"chapter")) echo "selected"; }?>>View Chapters</option> <option value="topic" <?php if(isset($_POST['selectview'])) { if(!strcmp($_POST['selectview'],"topic")) echo "selected"; }?>>View Topics</option> <option value="lecture" <?php if(isset($_POST['selectview'])) { if(!strcmp($_POST['selectview'],"lecture")) echo "selected"; }?>>View Lectures</option> <option value="assignment" <?php if(isset($_POST['selectview'])) { if(!strcmp($_POST['selectview'],"assignment")) echo "selected"; }?>>View Assignment</option> <option value="evaluationtest" <?php if(isset($_POST['selectview'])) { if(!strcmp($_POST['selectview'],"evaluationtest")) echo "selected"; }?>>View Evaluation Test</option> <option value="exampaper" <?php if(isset($_POST['selectview'])) { if(!strcmp($_POST['selectview'],"exampaper")) echo "selected"; }?>>View ExamPapers</option> </select> </div> </div> <div> <input type="submit" value="View" onclick="checkview()" name="btn" class="blue-btn" /> </div> </div> </form> 在我的代码中不起作用。我希望当用户留空时,JS应该停止表单发布。 这是我的代码:

HTML:

<script type="text/javascript">
function checkview()
{
    var classname1 = $('#selectclass').val();
    var select_view = $('#selectview').val();
    if (classname1 == 'none' || select_view == 'none')
        {
            alert('Please fill all fields!!');
            return false;
        };
}
</script>

这是我的JS:

{{1}}

当我发布此表单时,它会显示警报(未选择任何选项),然后我希望它不会被发布但是它会被发布。我无法找到阻止此表单发布的方法!!

P.S。我第一次在这里问一个问题。所以请不要担心我的愚蠢错误 提前谢谢!

1 个答案:

答案 0 :(得分:1)

将其作为回报

 <form name="MyForm" method="post" action="" onsubmit="return checkview() ">

最后将其作为

 <input type="submit" value="View"  name="btn" class="blue-btn" />

onsubmit是一个js事件,在提交表单时根据布尔值调用doesn't submitsubmits