Jelle
Jelle

Reputation: 798

Setting input value using document.getElementById not truely setting the value

I have an input:

<input type="text" class="input" name="email" id="email" value="" disabled>

And JavaScript:

$email = "[email protected]";

function setEmail(email) {
        document.getElementById("email").value = email;
    }

    window.onload = setEmail($email);

Now, it does show the email in the input field just how i want it to: it does show stackemail@emails.com

But it doesn't set the value when i inspect the element: the value = ""

Even when i change the value inside the inspect element, it stays "[email protected]"

Now i need the value to be the same as what it is showing Why is it not doing so?

Upvotes: 3

Views: 9865

Answers (2)

Diego Peinador
Diego Peinador

Reputation: 81

Works anyway... the inspector not show ur changes, if u want try use setAttribute function but works fine

    $email = "[email protected]";

    function setEmail(email) {
          document.getElementById("email").value = email;
    //if u want change attr.. try works too
      //document.getElementById("email").setAttribute('value',email);
        }
    function getEmail(){
      return document.getElementById("email").value;
    }

    document.addEventListener("DOMContentLoaded", function(event) { 
      setEmail($email);
      console.log('value: ' + getEmail());
    });
<input type="text" class="input" name="email" id="email" value="" disabled />

Upvotes: 2

Pranav C Balan
Pranav C Balan

Reputation: 115222

You are updating it value property of the DOM element and not its value attribute. To reflect in the markup use setAttribute() which is using to update an attribute.

function setEmail(email) {
   document.getElementById("email").setAttribute('value', email);
}

$email = "[email protected]";

function setEmail(email) {
  document.getElementById("email").setAttribute("value", email);
  document.getElementById("email2").value = email;
}

window.onload = setEmail($email);
<input type="text" class="input" name="email" id="email" value="" disabled>

<input type="text" class="input" name="email" id="email2" value="" disabled>

Upvotes: 8

Related Questions