Search code examples
jquerycheckboxrequireselected

Validate require if checkbox option is X


I am working on a form that requires validation. A small part of the form requires the user to choose between 2 options "Yes", "No". When no is selected I would need them to enter a reason, and otherwise if yes is selected, I don't need a reason (even the inputfield may be hidden then <- this is only doable via JavaScript I guess?)

How would I have to create this rule?

Let's say the part of the form looks like this

<form  id="Form" method="get" action="">
    <fieldset>
        <legend>form</legend>
    Yes:
        <input name="choice" type="radio" value="Yes"/>
        <br />
    No:
        <input name="choice" type="radio" value="No"/>
        <br />
        <label for="reaason">Reason</label>
        <input id="reason" name="reason"  />
    </fieldset>
</form>

Solution

  • http://jsfiddle.net/ZYqyC/

    wrapping label and textbox in a div

    <div id=reasondiv>
                <label for="reaason">Reason</label>
                <input id="reason" name="reason"  />
     </div>
    

    then jquery:

    $("#reasondiv").hide();
    $("input[name=choice]:radio").click(function(){
    
       if($(this).val()=='Yes')
          $("#reasondiv").show();
       else
           $("#reasondiv").hide();
    
    });