duanhuo7441 2015-02-01 14:06
浏览 21
已采纳

表单提交时未执行Javascript验证

I have javascript that is trying to validate a form, more specifically the "type=date" part of the form. But for some reason when I submit the form it doesn't even run the script (I think?) and just goes to the page specified in

here is the code

<!-- 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条回答 默认 最新

  • douwen0612 2015-02-01 15:03
    关注
    <!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>
    

    works as expected

    Note: The submit button is OUTSIDE of the form, and when clicked, the script is executed and submits the form programatically, if everything is right.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题