Home > other >  How to set the "value" and "for" attribute using Object.assign
How to set the "value" and "for" attribute using Object.assign

Time:01-19

How do I set the value of an element using Object.assign()? All other attributes seem to show up except "value"for an <input> and "for" for a <label>. Here's the code:

window.onload = function createForm () {

    // Form header >>>>
    const formHeaderText = document.createTextNode("Form");
    headerEl.appendChild(formHeaderText);
    container.appendChild(headerEl);

    // Form element >>>
    Object.assign(formEl, {
        name: "inputForm",
        id: "myForm"
    });
   container.appendChild(formEl);

    // Name Label >>>
    const nameLabelText = document.createTextNode("Name");
    labelElName.appendChild(nameLabelText);
    Object.assign(labelElName, {
        for: "iname",
    });
    formEl.appendChild(labelElName);

    // Name Input element >>>
    formEl.appendChild(inputElName);
    Object.assign(inputElName, {
        className: "inputs",
        id: "iname",
        name: "name",
        type: "text",
        placeholder: "Name",
        value: ""
    })

And what I get is:

<input  id="iname" name="name" type="text" placeholder="Name">

for the input and:

<label>Name</label>

for the label element.

CodePudding user response:

Since for is a reserved keyword in JavaScript, you need to use htmlFor property on label element, like this:

Object.assign(labelElName, {htmlFor: "iname"});

or

labelElName.htmlFor = "iname";
  •  Tags:  
  • Related