Question

I'm new to JavaScript, I need some help please!

I have these four links:
<a id="userName" href="javascript:showEditTextBox(this.id)"></a> <a id="occupation" href="javascript:showEditTextBox(this.id)"></a> <a id="country" href="javascript:showEditTextBox(this.id)"></a> <a id="industry" href="javascript:showEditTextBox(this.id)"></a>

And I also have a div, with a p and a form element. The p id is: id="editHeader". What I want to do is, to change the p value, depending on which link was clicked. So I want to compare the clicked link's id value with a String:

My function is like so, but it doesn't work:

function showEditTextBox (id){
if(id == "userName") 
    document.getElementById("editHeader").innerHTML = 'Change username';
else if(id == "occupation") 
    document.getElementById("editHeader").innerHTML = 'Change occupation';
    else if(id == "country")
            document.getElementById("editHeader").innerHTML = 'Change country';
    else if(id == "industry")
            document.getElementById("editHeader").innerHTML = 'Change industry';
}
Était-ce utile?

La solution

You should use # as href and the onclick event. Like so. Otherwise your javascript is correct.

Here is a working fiddle http://jsfiddle.net/FL7G8/1/

<a id="userName" href="#" onclick="showEditTextBox(this.id)">userName</a>
<a id="occupation" href="#" onclick="showEditTextBox(this.id)">occupation</a>
<a id="country" href="#" onclick="showEditTextBox(this.id)">country</a>
<a id="industry" href="#" onclick="showEditTextBox(this.id)">industry</a>

A cool effect would be to have href="#editHeader" for your anchor tags so that the window jumps to the element you are trying to change like so

<a id="industry" href="#editHeader" onclick="showEditTextBox(this.id)">industry</a>

Autres conseils

I'd change the links to be like the following:

<a id="userName" href="#" onClick="javascript:showEditTextBox(this.id)">username</a>

That should do it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top