1
votes

How would I combine the following html and js with scripts and what would it end up looking like? Thank you!

<label class="form-control">
  <input id="checkbox"     type="checkbox" name="purchased" />
  Purchased
</label> 


const cb = document.getElementById('checkbox');


//run every time the checkbox is set
cb.addEventListener('input', (e) => {
  console.log('changed');
  localStorage.setItem('purchased', e.target.checked);
});


//run once on page load, check if it is set in LS if yes then check it
const localPurchasedValue = localStorage.getItem('purchased');
if (localPurchasedValue === 'true') {
  cb.checked = true;
}
1

1 Answers

0
votes

Simply put the javascript in a script tag

<label class="form-control">
  <input id="checkbox" type="checkbox" name="purchased" />
  Purchased
</label> 


<script type="text/javascript">
const cb = document.getElementById('checkbox');


//run every time the checkbox is set
cb.addEventListener('input', (e) => {
  console.log('changed');
  localStorage.setItem('purchased', e.target.checked);
});


//run once on page load, check if it is set in LS if yes then check it
const localPurchasedValue = localStorage.getItem('purchased');
if (localPurchasedValue === 'true') {
  cb.checked = true;
}
</script>