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 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Linux权限管理相关操作(求解答)
  • ¥15 Bug traq 数据包 大概什么价
  • ¥15 在anaconda上pytorch和paddle paddle下载报错
  • ¥25 自动填写QQ腾讯文档收集表
  • ¥15 DbVisualizer Pro 12.0.7 sql commander光标错位 显示位置与实际不符
  • ¥15 android 打包报错