Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle 'required' property with jquery

Tags:

jquery

Here's the jsfiddle: http://jsfiddle.net/LEZ4r/77/

And the code itself:

<form action="demo_form.asp">
  <input type="text" name="first_name" value="" id="freeform_first_name"
    maxlength="150" required/>
  <div>
      Needs coupon? 
      <input type="radio" name="requires" value="yes">Yes</input>
      <input type="radio" name="requires" value="no" checked>No</input>
  </div>
        <div class="coupon" id="hidden">
            <input type="text" name="code"
            maxlength="150"/>
            </div>
        <input type="submit"/>
</form>

$(function(){
$('.coupon').toggle();  $('input:radio[name="requires"]').change(function() {
        var coup = $('.coupon');
        coup.toggle();
        if (coup.prop('required')) {
            coup.prop('required', false);
        } else {
            coup.prop('required', true);
        }
    });
});

When I check via the console in chrome, the required property is indeed set. When submitting the form though, it acts as though it's not. What's going wrong?

like image 410
user1769889 Avatar asked Jul 21 '14 14:07

user1769889


1 Answers

You're setting required on the div containing your input, not on the input itself.

You need to actually set required on the input:

coup.find('input').prop('required', true)
like image 180
meagar Avatar answered Nov 15 '22 05:11

meagar