I have a form of two elements, the first one is always required, while the second depends on the value of the first element, so if the value of first element equals to Fashion Designers
or Fashion Illustrators
, the second element display will be block and the second element will be required, while if the value of the first element is anything else, the second element will still displayed none and not required.
here is my code:
<form action="" method="post" id='career' enctype="multipart/form-data">
<div class="col-xs-12 col-lg-3 paddingleft">
<div style="margin-bottom:20px" class="form-group">
<select id="vacancy" name="vacancy" class="form-control">
<option value="" disabled selected>Select career</option>
<option value="Fashion Designers">Fashion Designers</option>
<option value="Fashion Illustrators">Fashion Illustrators</option>
<option value="Tailor">Tailors</option>
<option value="Tailor's Assistant">Tailor's Assistants</option>
<option value="Human Resources">Human Resources</option>
<option value="Marketing coordinators">Marketing Coordinators</option>
<option value="Sales coordinators">Sales Coordinators</option>
<option value="Accountants">Accountants</option>
<option value="Production Managers">Production Managers</option>
</select>
</div>
<div style="margin-bottom:20px" class="form-group">
<input type="file" name="portfolio" id="portfolio">
</div>
<div style="margin-bottom:20px" class="form-group">
<input type="submit" class="btn btn-default pull-right" data-toggle="modal" data-target=".bs-example-modal-sm" value="Submit">
</div>
</div>
</form>
<script type="text/javascript">
$('#career')
.bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
vacancy: {
validators: {
notEmpty: {
message: 'Vacancy is required.'
},
}
},
portfolio: {
validators: {
notEmpty: {
message: 'Portfolio is required.'
},
callback: {
message: 'Portfolio is required.',
callback: function (value, $field) {
if ($field.style.display === 'none') {
return true;
} else if (value != null) {
return true;
}
}
}
}
},
}
});
</script>
I got error: Uncaught TypeError: Cannot read property 'display' of undefined
I think the problem is your $field variable. Try using jQuery to validate the visibility:
!$field.is(':visible')
Try to debug this variable and check if you can use native javascript or jQuery is the best option.
Regards.