10

I want to set checkbox after the page has renderet to the matching state of the backend.

I implemented this function for that purpose what does the job so far

Updated to user-suggestion It doesn't matter if cbs[i].dataset.thvalue or cbs[i].dataset.value

 function updateCheckboxes () {

  let activeCheckbox = '<input type="checkbox" onclick="handleClickOnReduce()" checked>'
  let inactiveCheckbox = '<input type="checkbox" onclick="handleClickOnReduce()">'

  let cbs = document.getElementsByTagName('td')
  for (let i = 0; i < cbs.length; i++) {
    if (cbs[i].id === 'reduceCheckbox' || cbs[i].id === 'slCheckbox') {
      if (cbs[i].dataset.thvalue === 'true') {
        cbs[i].innerHTML = activeCheckbox
      }
      else {
        cbs[i].innerHTML = inactiveCheckbox
      }
    }
  }
}

HTML part, using Thymeleaf

    <td id="reduceCheckbox" data-th-value="${car.isReduced()}"></td>
    <td id="slCheckbox" data-th-value="${car.isSl()}"></td>

But the browser claims by printing out the value, that it is undefined, even if the value is set as you can see in the picture live from the browser.

enter image description here

Due to the docu my syntax should be correct?

https://www.w3schools.com/jsref/prop_option_value.asp

Any suggestion?

Ty

Anna Klein
  • 1,906
  • 4
  • 27
  • 56

3 Answers3

11

You HTML is invalid.

<td> elements do not have value attributes. (The link you reference is talking about <option>, not <td>).

Your browser is not mapping the JS value property onto your invented attribute.

If you want to add arbitrary data to an element, use a data-* attribute and read it using the dataset API.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    Thanks for this suggestion. I tried and updated my code, still have the same issue :-/ – Anna Klein Jul 25 '18 at 14:33
  • 2
    When you hyphenate data (i.e. data-th-value), you need to camel case (capitalise each word after the first) to reference. Thus, you should reference: `cbs[i].dataset.thValue` NOT `cbs[i].dataset.thvalue` – Nathan Stockton Aug 05 '18 at 04:04
4

It looks like my misunderstanding of the Thymeleaf syntax with regards to th-data led to that issue.

This is the fix:

<td id="reduceCheckbox" th:attr="data-value=${car.isReduced()}"></td>

Access via

 console.log(cbs[i].dataset.value)
Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45
Anna Klein
  • 1,906
  • 4
  • 27
  • 56
0

value is not valid attributes in td tag. you can use abbr attributes

<td id="reduceCheckbox" abbr="true"> <input type="checkbox" onclick="handleClickOnReduce()"> </td>

then you can get it

console.log(cbs[i].abbr)

Note: The abbr attribute is not supported in HTML5.

For HTML5 you can use headers attributes

<td id="reduceCheckbox" headers="true">
    <input type="checkbox" onclick="handleClickOnReduce()">
</td>

then you can get it

console.log(cbs[i].headers)