简体   繁体   中英

Form validation alert or message not displaying, but the validation works

I realized Safari isn't compatible with the HTML5 required feature, so I tried to add in a Javascript validation script. The script is blocking the customer from moving forward, but the alert OR message is now showing up.

<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);

Does anyone see anything that would be causing this to not display the alert or message? I've commented in the JS what parts are not working.

Your first option of the first select box contains an ID attribute like id="sizeoption" but the select box itself doesn't have an ID. Is this purposeful or by mistake?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM