jQuery Validate - Get value from select and based on the value make text input required field

前端 未结 1 599
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 13:53

I have a form with a select with 3 options \"Blank\", \"Yes\" and \"No\". I also have a text input which is part of this situation.

My HTML is as follows (Extract):

1条回答
  •  -上瘾入骨i
    2021-01-15 14:22

    You need to use a function() that returns true/false in conjunction with the depends property.

    rules: {
        medical: {
            required: true
        },
        medicaltext: { // <- NAME attribute of the input
            required: {
                depends: function() {
                    return ($("#medical").val() == "medyes");
                }
            }  
        },
    },
    

    Within the .validate() method, rules can only be assigned using the name attribute of each input element. Since I don't see any input with name="medcon", then this needs to be changed to match the name on the text input element.

    See documentation for depends: jqueryvalidation.org/validate/#rules


    For required to work on a select, you also need to change this line...

    
    

    into this...

    
    

    DEMO: http://jsfiddle.net/34oo7nrg/

    0 讨论(0)
提交回复
热议问题