简体   繁体   中英

Validation is working, but alert/message is not displaying

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 not showing up.

<div class="productdetailquantity"><?php echo"<form action='./itemsadded.php?view_product=$product_id' method='POST' id='formID'>"?>
<select class="productsize" id="sizeoption" name='size' required><span id="sizeoptionMSG" style="margin-left:6px;color:darkred;"></span>
    <option value=''>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 on those parts which are not working. Again, the validation works, but the message or alert is not displaying.

UPDATE:

I receive this error in the console:

Uncaught TypeError: Cannot set property 'innerHTML' of null

For this line:

document.getElementById('sizeoptionMSG').innerHTML = document.getElementById('sizeoption').value == '' ? 'Please, select a size' : ''; // Show message

UPDATE to show current JS code:

    <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
        if(document.getElementById('sizeoption').value == '') {
        document.getElementById('sizeoption').className += 'invalid-input';
    } // color field's border
        if (document.getElementById('sizeoption').value == '') document.getElementById('sizeoption').focus(); // Put cursor back to the field
        alert('Please, select a size.'); // error message
    }
}, false);
</script>

CSS for invalid-input:

.invalid-input {
border-color: #990000;
}

This is not an answer to your question because your html is invalid:

Here is me trying my best to change it to look ok:

<form action="itemsadded.php" method="post" id="formID">
  <div class="product-detail-quantity">
      <span id="sizeoptionMSG"></span>
      <select class="product-size" id="sizeoption" name="size" required>
          <option value="">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>
      <select class="product-quantity" name="quantity">
         <option value="1">1</option>
         <option value="2">2</option>
         <option value="3">3</option>
         <option value="4">4</option>
      </select>
  </div>

  <div class="product-detail-addbutton">
      <input type="hidden" name="product_id" value="<?=$product_id;?>">
      <button type="submit" class="add-to-cart" name="add_to_cart">Add to cart</button>
  </div>
</form>

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

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

You had tags that were wrongly opened and closed. Also, you are not allowed to have span inside select .

EDIT: I just realized that you didn't have consistency in double or single quotes. I just changed the code above with consistent double quotes. I, personally love double quotes, so, I always keep everything in double quotes. Also, never wrap HTML inside a PHP echo. Use PHP echo or <?=$var;?> only for the needed parts (just like I did it).

EDIT: Also forgot to mention. Do not use <br> to arrange layout elements. <br> should only be used with text. If you need margins between the selects, just add something like .productdetailquantity select { margin: 5px 0; } .productdetailquantity select { margin: 5px 0; } in your CSS. This is just an example. Also, for having readable CSS classes, separate each word using dash/hyphen or underscore. Eg productsize becomes product-size

EDIT: Also, never do "./itemsadded.php?view_product=$product_id" with forms if you are trying to insert an item to db or whatever. You are already sending $product_id through a field, so "itemsadded.php" is just enough. You also don't need the "./" because it is already checking the path relative to current path.

EDIT: For the following line:

document.getElementById('sizeoption').style.borderColor = document.getElementById('sizeoption').value == '' ? 'darkred' : ''; // color field's border -- NOT SHOWING UP

don't do that. You set the styles for things like that in class and just add class through JS:

if(document.getElementById('sizeoption').value == '') {
    document.getElementById('sizeoption').className += ' invalid-input';
}

Also, I think in overall scenario, jQuery will fit your needs better. With jquery, the code above will look like:

 $('#formId').submit(function(e) {
     if(e.target.checkValidity()) {
         e.preventDefault();
         if($('#sizeoption').val() == '')) {
             $('#sizeoption').addClass('invalid-input');
         }
         // ...
     }
 }

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