3

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?

1
  • 1
    to set the value attribute, use .setAttribute. check this fiddle for reference: jsfiddle.net/evhzofz2/1 (and inspect elements) Commented Jan 11, 2017 at 15:04

2 Answers 2

8

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>

Sign up to request clarification or add additional context in comments.

1 Comment

fiddle with the two elements printed (if needed): jsfiddle.net/evhzofz2/1 (using both setAttribute and value)
2

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 />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.