表单提交时未执行Javascript验证

时间:2015-02-01 14:06:30

标签: javascript php html5 forms

我有javascript试图验证表单,更具体地说是表单的“type = date”部分。但由于某种原因,当我提交表单时,它甚至没有运行脚本(我想?)并且只是转到

中指定的页面

这是代码

<!-- script to make sure only weekdays are selected -->
<script>
var date = document.querySelector('[type=date]');

function noWeekends(e){

    var day = new Date( e.target.value ).getUTCDay();

    // Days in JS range from 0-6 where 0 is Sunday and 6 is Saturday

    if( day == 0 || day == 6 ){
        e.target.setCustomValidity('Please select a weekday.');
        return false;
    } else {
        e.target.setCustomValidity('');
    }
}
date.addEventListener('input',noWeekends);
</script>
<!--============================================================
=======================form starts here=========================-->

<form action="confirm_booking.php" onsubmit="noWeekends()" method='post'> 
<?php
echo "Room: ";
select_room();
?>
week starting: <input type=date name='WeekStart'/>

<input type="submit" value="Book Room">
</form>

1 个答案:

答案 0 :(得分:0)

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8" />
    <title></title>
    </head>
    <body>
        <form id="form" action="confirm_booking.php" method='post'> 
        <?php
        echo "Room: ";
        select_room();
        ?>
        week starting: <input id="date" type=date name='WeekStart'/>
        </form>
        <input type="submit" value="Book Room" onclick="noWeekends()">
        <script>
        function noWeekends(){
            var date = document.getElementById('date');
            var day = new Date( date.value ).getUTCDay();
            console.log(day);
            if( day == 0 || day == 6 ){
                date.setCustomValidity('Please select a weekday.');
                return false;
            } else {
                date.setCustomValidity('');
                document.getElementById("form").submit();
            }
        }
        </script>
    </body>
</html>

按预期工作

注意:提交按钮位于表单的外部,单击时,执行脚本并以编程方式提交表单,如果一切正常。