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
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
Share Improve this question asked Oct 15, 2013 at 8:47 qwertzuiopqwertzuiop 7352 gold badges11 silver badges26 bronze badges 03 Answers
Reset to default 5You'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;
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 = "";
}
}
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