Home > Software engineering >  How to set checkboxes to true using label for value rather than Id, Javascript?
How to set checkboxes to true using label for value rather than Id, Javascript?

Time:10-02

I'm new to Javascript and learned that you can use JS to complete certain actions in the Dev console of Chrome. I have this task where we want to set certain checkboxes to true. I've used the code below in the dev console and it works but it requires the Id. The only information that is constant across all these webpages is the label element. Is there anyway where we can get the elements Id of a checkbox using the label element's value and the label for value, then set that element to true? Thank you and any/all help is appreciated.

Here is the code I used in the dev console of Chrome to set the checkbox to true, this is good when you know the Id.

document.getElementById("00N3t00000GCsiX").checked = true;

Checkboxes on the webpage

Here is an example element showing the Id of the input and the label for that Id. Ideally, we would like to set the input element to true using the label value rather than the Id:

<input id="00N3t00000GCsiX" name="00N3t00000GCsiX" type="checkbox" value="1">
<label for="00N3t00000GCsiX">Reformatted CTI Phone</label>

CodePudding user response:

You can use a loop over all the <label> elements searching for a specific .textContent attribute. Like this:

function setLabelToTrue(text) {
  const labels = document.getElementsByTagName('label');
  for (const label of labels) {
    if (label.textContent === text) {
      document.getElementById(label.getAttribute('for')).checked = true;
    }
  }
}

setLabelToTrue('Reformatted CTI Phone'); // sets the checkbox to true
<input id="00N3t00000GCsiX" name="00N3t00000GCsiX" type="checkbox" value="1">
<label for="00N3t00000GCsiX">Reformatted CTI Phone</label>

  • Related