Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Conditionally require a field
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Toggle field requirement</title>
<meta name="description" content="A clean-room implmentation of conditional field requirement.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
$('#no-doi, #mint-doi').change(function(e){
var $target = $(e.target),
$field = $('#publisher')
if ($target.attr('id') == 'mint-doi') {
$field.attr('required', 'true');
} else {
$field.removeAttr('required');
}
});
});
</script>
<style>
fieldset {margin:1em 0}
form {max-width:30em}
label {display:block}
</style>
</head>
<body>
<form action="/">
<fieldset>
<legend>Create Work</legend>
<div>
<label for="title">Title</label>
<input id="title" name="title" required="true"/>
</div>
<div>
<label for="publisher">Publisher</label>
<input id="publisher" name="publisher"/>
</div>
<fieldset>
<legend>DOI</legend>
<label for="no-doi">
<input type="radio" name="doi" id="no-doi" checked="checked"/>
I don't need a DOI
</label>
<label>
<input type="radio" name="doi" id="mint-doi"/>
Create a DOI for me
</label>
</fieldset>
<input type="submit" value="Submit"/>
</fieldset>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.