I like to use my notes page for lists, especially shopping lists, but the markdown library I'm using (Parsedown) doesn't support checkboxes.
A quick function later and I had support. This takes the raw markdown prior to display and does a simple replace:
function parseMarkdownCheckboxes($text) {
$text = preg_replace('/\[ \]/', '<input type="checkbox" class="checkbox">', $text);
$text = preg_replace('/\[x\]/', '<input type="checkbox" checked class="checkbox">', $text);
return $text;
}
Great. But that only converts the markup for viewing. What if I could check/uncheck boxes and have them automatically update the note in real time?
I broke it down into sections then started asking ChatGPT for some code examples. As usual, it couldn't give me exactly what I wanted but was a great place to start.
Now, when I click a checkbox the following things happen:
- some JavaScript makes an array of all the checkboxes in a note (within the containing div)
- it gets the raw markdown text from a hidden textarea and splits it into an array of lines
- it reduces that further into lines that contain a checkbox
- using the index of the item clicked it update the relevant line from the markdown, joins them back together and replaces the textarea value
- it then makes an AJAX call to another file which updates the note content in the database in the background
To make things even better, a quick bit of CSS fades the checked items:
li:has(input[type="checkbox"]:checked) {
opacity: 25%;
}
Update After wrangling with ChatGPT some more (and by wrangling I mean pointing out where it got things wrong) I've now also got it moving checked items to the bottom of the list and unchecking an item will move it to the top.