Created
July 14, 2017 15:10
-
-
Save mitchlloyd/3aa1170178eb0e34db9a0191ca816c1e to your computer and use it in GitHub Desktop.
vanilla-imperative-example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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