0

I have a list with several checkboxes dynamically generated by php inside a div, so they do not have an id or a name.

I can read the full div content with

var list = document.getElementById("myList").innerHTML;

the variable list looks similar to this:

<li><input type="checkbox">text 1</li>
<li><input type="checkbox">text 2</li>
<li><input type="checkbox">text 3</li>
<li><input type="checkbox">text 4</li>
.... (unknown number of entries)

What I need to do is to check if the checkbox has been checked or not prior to sending the data to a php file.

I would like to have something similar to this

<li>(checked) text 1</li>
<li>(not checked) text 2</li>
<li>(checked) text 3</li>
<li>(checked) text 4</li>

How can I do this ?

2
  • 1
    Are you just looking for the :checked CSS pseudo-class selector? Commented Aug 13, 2023 at 6:25
  • actually no. When a button on the page is pressed, I need to read the status of each checkbox and send it to a php file to be analyzed. Commented Aug 13, 2023 at 6:30

1 Answer 1

1

You can just verify the checked property of the checkbox. You don't have to access the innerHTML, you can run through the child elements of the list, like so:

const list = document.getElementById("myList")
const checkboxes = list.getElementsByTagName("input");
const button = document.getElementById("show");

// Calls showText when button is clicked
button.addEventListener("click", showText);

function showText(){
  let output = "";
  for (const checkbox of checkboxes) {
    // is it checked?
    const checked = checkbox.checked;

    // get just the text of the <li>-element
    const html = checkbox.parentElement.innerText;

    // build the string together
      output += "<li>(" + ((checked) ? "checked":"not checked") + ") " + html + "</li>\n";
  }
  // replace the content of the parent <ul>
  list.innerHTML = output;
}
<ol id="myList">
<li><input type="checkbox" name="cb1">1</li>
<li><input type="checkbox" name="cb2">2</li>
</ol>
<button id="show">READY</button>

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. If I correctly understand your code, it loops through all the input elements inside the list variable and show the result in the console. How can I replace <input type="checkbox"> with checked / not checked as in my question ?
Just edited the code.
@dequid I stuck your code into a snippet so we can see it run. Also added a button with an event listener so the checkboxes are visible when the page first loads (until we click the button). Feel free to revert my changes if you don't like them.
solution works perfectly! please mark this question as completed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.