javascripthtmldom-node

JS DOMNode checkbox set value


I'm using HTML template tags to render content via JS (no jQuery or anything else).

Using content.cloneNode(true) to clone the nodes, set the content, values, ... and at the end I append it to a node inside the HTML. Thats working fine for every element so far. But currently I have an issue with input type checkbox. I can't set the value. (I don't mean the checked status)

The problem is, when I set the value it's not part of the HTML element thats getting rendered. Not visible with the browser dev tools and also document.querySelector(...).value will return an empty string.

My goal is to be able to fetch on a button click the values of all enabled (checked) checkboxes for an AJAX request.

Code example: https://jsfiddle.net/3gnLv67x/


Solution

  • I haven't found the reason why the value is not getting set. But since it's only a simple input field I changed to the code to create the element instead of using a template for that.

    This way is working.

    const checkbox = document.createElement("input");
    checkbox.type = 'checkbox';
    checkbox.name = 'selected[]';
    checkbox.className = 'select-box';
    checkbox.value = item.id;
    

    I'm still up to hear a solution how to get that working with templates.