Tim Schley
Tim Schley

Reputation: 47

Workaround for [required] fields not working on dropdown boxes

I am using Bootstrap 3 to validate fields in my forms, and I've found that using certain browsers, specifically ios safari, my [required] form items are not validated. To make up for this, I made a script that checks if an element has been marked as required and if that field has a value of '' then an alert comes up. It works great for text box fields, but for some reason, it doesnt seem to check dropdown boxes. I am using a placeholder on all of my dropdown boxes with the value of '' , so It should be seeing that those are not appropriately filled out.

My script is here

$("form").submit(function(e) {
    var mobile = "<?php echo $_SESSION['ads']; ?>";
    var ref = $(this).find("[required]");

    if(mobile == 0){
        $(ref).each(function(){
            if ( $(this).val() == '' )
            {
                alert("Required field should not be blank.");

                $(this).focus();

                e.preventDefault();
                return false;
            }
        }); 
    }return true;
});

Here's an example of one of my forms:

      <div class="form-group required">
        <label for="donationType">Type</label>
        <select class="form-control" name="donationType" id="donationType" style="min-width: 140px;" required>
          <option value="" disabled selected>-</option>
          <option>Item</option>
          <option>Mileage</option>
          <option>Money</option>
          <option>Time</option>
        </select>
      </div>

Any insight into this would be greatly appreciated. Or any other ways to validate on a browser that doesn't support normal bootstrap validation.

Upvotes: 1

Views: 68

Answers (1)

Gavriel
Gavriel

Reputation: 19237

By adding

$(this).val() == null || 

it works for me in Safari as well:

$("form").submit(function(e) {
    var mobile = "0";
    var ref = $(this).find("[required]");
console.log(ref);
    if(mobile == 0){
console.log(0);
        $(ref).each(function(){
            if ( $(this).val() == null || $(this).val() == '' )
            {
                alert("Required field should not be blank.");

                $(this).focus();

                e.preventDefault();
                return false;
            }
        }); 
    }
    return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="form-group required">
        <label for="donationType">Type</label>
        <select class="form-control" name="donationType" id="donationType" style="min-width: 140px;" required>
          <option value="" disabled selected>-</option>
          <option>Item</option>
          <option>Mileage</option>
          <option>Money</option>
          <option>Time</option>
        </select>
      </div>
  <input type="submit" value="submit"/>
  </form>

Upvotes: 2

Related Questions