最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - GetElementById can't get value - Stack Overflow

programmeradmin2浏览0评论

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 0
Add a ment  | 

3 Answers 3

Reset to default 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;

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

发布评论

评论列表(0)

  1. 暂无评论