0

How would you go about validating a field if a dropdown equals to a certain value.

Example:

HTML

<form id="foo">
    <!-----Dropdown----->
    <select name="budget_type">
        <option value="fixed" <?php if($budget_type=="fixed" ){echo "selected";} ?> >Fixed</option>
        <option value="hourly" <?php if($budget_type=="hourly" ){echo "selected";} ?> >Hourly</option>
    </select>
    <!-----Field----->
    <input id="dollar" type="text" name="budget" style="text-indent:17px;" value="<?php echo $budget; ?>" />
</form>

jQuery:

$('#foo').validate({
    rules: {
        budget: {
            required: true,
            notEquals: "0",
            digits: true,
            min: 50,
        }
    },

    messages: {
        budget: {
            required: "Please enter a value",
            min: "Minimum $ {0}",
        }
    }
});

So, if budget_type is fixed then minimum budget is 50 but if budget_type is hourly then minimum budget is 10. I tried the if() function but don't really know how and where to put the code.

1 Answer 1

1

You can change the min rule to pass the value dynamically

jQuery(function($) {
  $('#foo').validate({
    rules: {
      budget: {
        required: true,
        digits: true,
        min: function() {
          return $('select[name="budget_type"]').val() == 'fixed' ? 50 : 10
        },
      }
    },
    messages: {
      budget: {
        required: "Please enter a value",
        min: "Minimum $${0}",
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
<form id="foo">
  <select name="budget_type">
    <option value="fixed">Fixed</option>
    <option value="hourly">Hourly</option>
  </select>
  <input id="dollar" type="text" name="budget" style="text-indent:17px;" value="20" />
  <input type="submit" value="Save" />
</form>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Worked perfect. One more thing. Can you show me how to remove the space in between $ and {0} in messages. if I remove the space it doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.