Skip to content

Instantly share code, notes, and snippets.

@esmevane
Created May 17, 2012 15:06
Show Gist options
  • Save esmevane/2719524 to your computer and use it in GitHub Desktop.
Save esmevane/2719524 to your computer and use it in GitHub Desktop.
Click warning example
<html>
<head>
<title>Checkbox Complete Demo</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
</head>
<body>
<form action="#" class="no-submit">
<h1>Show/hide submit based on whether a checkbox is checked or not</h1>
<p>
<h2>The scenario</h2>
<ul>
<li>
There are two elements in this form, a input of type checkbox and an input of type submit.
</li>
<li>
We don't want the submit to be available to the user until the checkbox has been checked.
</li>
</ul>
</p>
<p>
<label>
<input type="checkbox" class='unhide' name="done">
I want the submit button to appear
</label>
</p>
<p>
<input class="hide" type="submit" value="Commit">
</p>
</form>
</body>
<script type='text/javascript'>
// This is a "document ready" wrapper. It makes sure that the code only executes once all
// the html, css and js in the page is loaded and ready.
$(function() {
// We're going to do this with JavaScript events.
// We'll use jQuery to observe the events and send code out when they're triggered.
// $ is the namespace for all jQuery code. To get an HTML element in jQuery, the syntax is:
// $("tag-type.element-class#element-id")
// jQuery uses CSS style selectors.
// tag-type = This is the actual name of the tag: input, for example.
// element-class = This is listed in the class part of the tag. Prefixed with a '.'
// element-id = This is listed in the id part of the tag. Prefixed with a '#'
// Here, we want to select all elements with the 'unhide' class, and tell it to activate some code
// when it is clicked.
// The code in question is .toggle() - toggle will hide elements if they are visible, or
// show them if they are hidden.
$('.unhide').on('click', function(event) {
$('.hide').toggle();
});
// Here we want to catch the event object, and call .preventDefault() on it - this is just for the
// sake of this demo and I don't recommend just throwing it into production code. It says, "Don't
// do the default thing that this normally would do", which is in this case, submitting the form.
$('.no-submit').on('submit', function(event) {
event.preventDefault();
})
// This selects any element with the hide class, and hides it.
$('.hide').hide()
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment