表单验证警报或消息未显示,但验证有效

时间:2015-06-22 15:38:08

标签: javascript jquery html forms

我意识到Safari与HTML5所需功能不兼容,因此我尝试添加Javascript验证脚本。该脚本阻止客户继续前进,但现在显示警报OR消息。

<div class="productdetailquantity"><?php echo"<form action='./itemsadded.php?view_product=$product_id' method='POST' id='formID'>"?>
    <select class="productsize" name='size' required><span id="sizeoptionMSG" style="margin-left:6px;color:darkred;"></span>
        <option value='' id="sizeoption">Select a Size</option>
        <option value='Small'>Small</option>
        <option value='Medium'>Medium</option>
        <option value='Large'>Large</option>
        <option value='XL'>XL</option>
     </select><br><br>
     <select class="productquantity" name='quantity'>
         <option value='1'>1</option>
         <option value='2'>2</option>
         <option value='3'>3</option>
         <option value='4'>4</option>
     </select>
</div><br><br>
<div class="productdetailaddbutton">


  <?php 
echo "<input type='hidden' name='product_id' value='$product_id' />
        <input type='submit' class='addtocart' name='add_to_cart' value='Add to cart' />";
    ?>


<script>
    var form = document.getElementById('formID'); // form has to have ID: 

<form id="formID">
form.noValidate = true;
form.addEventListener('submit', function(event) { // listen for form submitting
        if (!event.target.checkValidity()) {
            event.preventDefault(); // dismiss the default functionality
            document.getElementById('sizeoptionMSG').innerHTML = document.getElementById('sizeoption').value == '' ? 'Please, select a size' : ''; // Show message, NOT SHOWING UP
            document.getElementById('sizeoption').style.borderColor = document.getElementById('sizeoption').value == '' ? 'darkred' : ''; // color field's border -- NOT SHOWING UP
            if (document.getElementById('sizeoption').value == '') document.getElementById('sizeoption').focus(); // Put cursor back to the field -- NOT WORKING
            alert('Please, select a size.'); // error message -- NOT WORKING
        }
    }, false);

是否有人看到任何可能导致此操作无法显示提醒或消息的内容?我在JS中评论了哪些部分不起作用。

1 个答案:

答案 0 :(得分:0)

第一个选择框的第一个选项包含ID属性,例如 id =“sizeoption”,但选择框本身没有ID。这是故意的还是错误的?

相关问题