Skip to content

Instantly share code, notes, and snippets.

@danhorst
Created June 23, 2014 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danhorst/dd7536e940fc212c8887 to your computer and use it in GitHub Desktop.
Save danhorst/dd7536e940fc212c8887 to your computer and use it in GitHub Desktop.
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