3

Do you know why this

function deleteInputOnClick(input){
    champ = document.getElementById(input);
    if(champ.value =='E-mail'){
        champ.value = "";
    }
}

works but this way

function deleteInputOnClick(input){
    champ = document.getElementById(input).value;
    if(champ=='E-mail'){
        champ= "";
    }
}

it doesn't ?

It's probably a stupid little error but I really don't see where it could be.

Thank's

qwertzuiop
  • 685
  • 2
  • 10
  • 24

3 Answers3

5

You're not setting the value back on the element in the second way, you're just assigning it to a local variable, you still need to do document.getElementById(input).value = champ;

Fiona - myaccessible.website
  • 14,481
  • 16
  • 82
  • 117
  • 2
    The first way is the correct way, because champ becomes a DOM object and you can manipulate the value anytime, while in the second way you can extracting the value into a variable, so you cant set it back using same variable – Ahmad Oct 15 '13 at 08:53
3

That is because is champ is a variable that has been assigned the value of the input element.

Changing its value will not change the value of the input (as it is not a two-way binding, you just assigned the value to it)

So you need to directly target the value property of the input to alter its value


If you are trying to avoid using the .value to a lot of places you can cache both the input element and its value for different uses..

function deleteInputOnClick(input){
    var champ = document.getElementById(input),
        value = champ.value;
    if(value=='E-mail'){
        champ.value = "";
    }
}
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
2

document.getElementById(input).value returns a string value while document.getElementById(input) returns a reference (an object). So in one case only the value of the local variable is changed, in the other the original object still links to the DOM value.

Have a look at this question: Javascript by reference vs. by value

Community
  • 1
  • 1
Matt Zeunert
  • 16,075
  • 6
  • 52
  • 78