Last active
March 18, 2017 10:40
-
-
Save abhilashsajeev/711af0cf7d7e06f22ee3616974cc50af to your computer and use it in GitHub Desktop.
update p tag based on checkbox
This file contains hidden or 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
<html> | |
<head> | |
<script> | |
document.addEventListener('DOMContentLoaded', addListeners, false); | |
var checkedItems = []; | |
var animals = [] ; | |
function getIndex(value){ | |
return checkedItems.indexOf(value); | |
} | |
function handleCheck(e) { | |
if(e.target.checked){ | |
checkedItems.push(e.target.value) | |
} else { | |
checkedItems.splice(getIndex(e.target.value), 1); | |
} | |
createText() | |
} | |
function createText() { | |
var p = document.getElementById('selected_animals') ; | |
if(checkedItems.length && checkedItems.length === animals.length){ | |
p.innerText = "You've selected all three, yay!\n"; | |
} else if(checkedItems.length === 0){ | |
p.innerText = "Please select atleast one animal!"; | |
} else { | |
var text = checkedItems.reduce(function(acc, val, index){ | |
return index === 0 ? acc + val : acc +' and '+ val; | |
}, "You've selected "); | |
p.innerText = text + '!'; | |
} | |
} | |
function addListeners() { | |
animals = document.getElementsByName('animals') | |
animals.forEach(function(i){ | |
i.addEventListener('click', handleCheck) | |
}); | |
} | |
</script> | |
</head> | |
<body> | |
<div> | |
<input type="checkbox" value="Cat" name="animals">Cat | |
<br> | |
<input type="checkbox" value="Dog" name="animals">Dog | |
<br> | |
<input type="checkbox" value="Hamster" name="animals">Hamster | |
<br> | |
<p id="selected_animals">Please select atleast one animal!</p> | |
</div> | |
</body> | |
<html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment