Question

Project: Shopping List

I have created a function that will take input from a form. I am able to display what the user entered. Now I want to add a checkbox next to item displayed, so I can eventually give the option to check the item and remove it.

This is my function:

function addItem() {
    var item = [];
    item = document.getElementById('items-listed');
    item.innerHTML += "<li>" + document.form.itemEntered.value + "</li>";
    // item.innerHTML += "<li><input type="checkbox" />" + document.form.itemEntered.value + "</li>";
}

I attempted to create the checkbox but it was not working, so I commented it out.

Here is the project running in Code Pen

http://cdpn.io/JGCDB

Was it helpful?

Solution

This should do it:

item.innerHTML += "<li><input type='checkbox'>" + document.form.itemEntered.value + "</li>";

The issue you experienced is called escaping.

You are generating a string in JS using double-quotes so if you want to use a literal double-quote inside your string then you need to escape it, please study the code below:

item.innerHTML += "<li><input type=\"checkbox\">" + document.form.itemEntered.value + "</li>"; //good
item.innerHTML += '<li><input type="checkbox">' + document.form.itemEntered.value + '</li>'; //good
item.innerHTML += '<li><input type=\'checkbox\'>' + document.form.itemEntered.value + '</li>'; // good

item.innerHTML += "<li><input type="checkbox">" + document.form.itemEntered.value + "</li>"; //bad
item.innerHTML += '<li><input type='checkbox'>' + document.form.itemEntered.value + '</li>'; //bad

The devil is always in the details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top