Home > Net >  How to change the value attribute of a dropdown option?
How to change the value attribute of a dropdown option?

Time:10-24

So I want to change the value attribute of this dropdown option in the select form using JS DOM.

<select name="Party">
      <option id="partyreg" value="Party">Party</option>
</select>

However this doesn't seem to work:

document.getElementById("partyreg").value = partyCode;

Any ideas?

CodePudding user response:

I think the problem is that partyCode is not defined. I think you intend to use a string? Something like:

document.getElementById("partyreg").value = "partyCode";

Which doesn't generate an error in the console like your code does.

Note that this changes the value of the option, not the "value" you see in the browser window.

CodePudding user response:

try below code:

document.getElementById("partyreg").setAttribute('value', partyCode)

CodePudding user response:

Hey @Zak,

If you want to change attributes value, then you could do like this:-

document.getElementById('partyreg').id = 'partyCode';

or you can also do that as wall

document.getElementById('partyreg').setAttribute("id","div2")

======================================================================

<html>
<head>  
 <style>
        #partyreg {
            background: green;
        }
  
        #partyCode {
            background: blue;
        }
    </style>
</head>
<body id='partyreg'>
    <button onclick="document.getElementById(
        'partyreg').id = 'partyCode';">
        click here
    </button>
</body>
  
</html>

CodePudding user response:

document.getElementByID("partyreg").setAttribute("value", partyCode)

  • Related