Home > OS >  How do I assign value of button.setAttribute('name', 'value') a javascript varia
How do I assign value of button.setAttribute('name', 'value') a javascript varia

Time:02-27

First, here is the javascript code.

    const nameId = calledVariable.value // This variable is an input from a form

    // Create the button
    var payButton = document.createElement('input');
    payButton.setAttribute('type', 'button');
    payButton.setAttribute('value', 'UNPAID');
    payButton.setAttribute('class', 'unpaidButton');
    payButton.setAttribute('id', nameId); // This needs to be text of input
    payButton.setAttribute('onClick', 'updateButton(this.id)');

and this is the HTML result

<input type="button" value="UNPAID"  id="" onclick="updateButton(this.id)">

How do I get the HTML/javascript to recognize nameId as it's value?

CodePudding user response:

And I solved my own question... use the following in the code...

payButton.setAttribute('id', `${nameId}`);

This is a Facepalm moment...

CodePudding user response:

You don't need to use ${...} to pass the var value to the setAttribute function. Use only the variable name. Like that:

const nameId = 123;
const payButton = document.querySelector('button');
console.log('before', payButton)
payButton.setAttribute('id', nameId);

const check = document.querySelector('button');
console.log('after',check)
<button>button</button>

  • Related