简体   繁体   中英

How do I assign value of button.setAttribute('name', 'value') a javascript variable

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" class="unpaidButton" id="" onclick="updateButton(this.id)">

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

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>

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

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

This is a Facepalm moment...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM