Skip to content

Instantly share code, notes, and snippets.

@mitchlloyd
Created July 14, 2017 15:10
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 mitchlloyd/3aa1170178eb0e34db9a0191ca816c1e to your computer and use it in GitHub Desktop.
Save mitchlloyd/3aa1170178eb0e34db9a0191ca816c1e to your computer and use it in GitHub Desktop.
vanilla-imperative-example
<!-- The initial UI -->
<title>Vanilla</title>
<div class="has-dog-question">
<p>Do you have a dog?</p>
<label>
<input type="radio" name="hasDog" value="yes">
Yes
</label>
<label>
<input type="radio" name="hasDog" value="no">
No
</label>
</div>
<br><br>
<div class="dog-name-question" style="display: none">
<label>What is the name of your dog?</label><br>
<input>
</div>
<br><br>
<button disabled>Save</button>
<br><br>
<div id="output"></div>
<script>
// Get references to important bits of DOM
let dogNameQuestion = document.querySelector('.dog-name-question');
let dogNameQuestionInput = document.querySelector('.dog-name-question input');
let hasDogQuestion = document.querySelector('.has-dog-question');
let hasDogQuestionYes = document.querySelector('.has-dog-question input');
let saveButton = document.querySelector('button');
let output = document.querySelector('#output');
// When the user answers whether or not they have a dog...
hasDogQuestion.addEventListener('change', function({ target }) {
if (target.value === 'yes') {
dogNameQuestion.style.display = 'block';
saveButton.disabled = !dogNameQuestionInput.value.length;
} else {
dogNameQuestion.style.display = 'none';
saveButton.disabled = false;
}
});
// When the user types in the dogName field...
dogNameQuestion.addEventListener('input', function({ target }) {
var dogName = target.value;
if (dogNameQuestionInput.value.length) {
saveButton.disabled = false;
} else {
saveButton.disabled = true;
}
});
// When the user submits the form...
saveButton.addEventListener('click', function({ target }) {
var data = {};
if (hasDogQuestionYes.checked) {
data.hasDog = true;
data.dogName = dogNameQuestionInput.value;
} else {
data.hasDog = false;
}
output.innerHTML = JSON.stringify(data);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment