Reputation: 3
I have searched on this website and tried all the suggestions and have not been able to get the text field to not be required when selecting 'No' on the radio button.
At the moment if 'Yes' and 'No' are not checked, the text field is not required so form will submit. But if either fields are checked, then it becomes required even for 'No' :-(
I have the demo here: https://jsfiddle.net/ba9ahpyx/
I only want the 'field_2' input to be required if 'Yes' is selected on the 'field_1' radio button.
I will be hiding the text field when 'No' is selected but have removed that code for now to keep it simple.
HTML
<form method="post" action="#">
<div>
<div class="radio">
<span class="label">Do you have your own website? (required)</span>
<div>
<label><input type="radio" name="field_1" value="Yes"> Yes</label>
<label><input type="radio" name="field_1" value="No"> No</label>
</div>
</div>
</div>
<div>
<label for="field_2">Website URL </label>
<input type="text" name="field_2" id="field_2" value="" />
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
Jquery
$(document).ready(function(){
$('input[name="field_1"]').change(function () {
if(this.checked) {
$('#field_2').prop('required',true);
} else {
$('#field_2').prop('required',false);
}
});
});
Thanks for your help.
Upvotes: 0
Views: 1233
Reputation: 2317
change jquery with following and it will work for you
$(document).ready(function(){
$('input[name="field_1"]').change(function () {
if($(this).val() =='Yes') {
$('#field_2').prop('required',true);
} else {
$('#field_2').prop('required',false);
}
});
});
Upvotes: 1