2

I am trying to do conditional validation using Jquery.Validate()

I have a select named selectAmount and an inpute named txtAmount

If selectAmount value = "Other"

I'd like for txtAmount to be required.

<div id="container">
    <form id="AddForm" method="POST" action="#">

                    <select name="selectAmount">
                        <option value="10">$10</option>
                        <option value="25">$25</option>
                        <option value="50">$50</option>
                        <option value="100">$100</option>
                        <option value="250">$250</option>
                        <option value="500">$500</option>
                        <option value="Other">Other</option>
                    </select>

                    <input name="txtAmount" type="text" placeholder="Enter Amount" />
            <button id="AddToCart">Add to Cart</button>
    </form>
</div>

Here's where I'm setting the rules. The problem I'm having is here:

"txtAmount": {
                required: function(element){
                    alert($("#selectAmount").val());
                    return false;

$('#selectAmount').val() //is always undefined

$(document).ready(function () {
  $("#AddForm").validate({
    rules: {
        "selectAmount" : {
            required: true
        },
        "txtAmount": {
            required: function(element){
                alert($("#selectAmount").val());
                return $("#selectAmount").val() == 'Other';
            }
        }
    },
    messages: {

        "selectAmount": {
            required: "Amount selection is required."
        },

        "txtAmount": {
            required: "Amount is required."
        }
    },
    submitHandler: function (form) { // for demo
        return false; // for demo
    }
});

});

http://jsfiddle.net/9YjH2/2/

Can anyone help?

1 Answer 1

2

You were actually very close. The # in $("#selectAmount") is telling jQuery to find the element with the id of selectAmount. But selectAmount is a name attribute not an id. So if you simply add the id=selectAmount attribute to your select everything works out fine. Here's a fiddle (with the alert commented out). Also here is some more info on jQuery selectors. If you do not want to add an id attribute, take a look at the attribute equals selector. However, I would recommend using the id.

So in the end just change this line:
<select name="selectAmount">
to
<select name="selectAmount" id="selectAmount">

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

Comments

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.