Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 810
Jelle Avatar asked Mar 22 '26 15:03

Jelle


2 Answers

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>
like image 199
Pranav C Balan Avatar answered Mar 25 '26 05:03

Pranav C Balan


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 />
like image 29
Diego Peinador Avatar answered Mar 25 '26 06:03

Diego Peinador



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!