2

I'm trying to get 2 values from the link

<a onclick="rev()" href="track_path">
  <span id="name">username</span> - <span id="track">track_name</span>
</a>

<script>
function rev() {
  var username = document.getElementById("name").value;
  var track = document.getElementById("track").value;
  return alert (username);
}
</script>

But when alert comes, it writes UNDEFINED....What is wrong?

7
  • 4
    Because you're using value when you should be using innerHTML/innerText. Commented Apr 19, 2017 at 12:39
  • .value will get the string assigned to value attribute, not what you want here. Use .textContent. And trim it. Commented Apr 19, 2017 at 12:40
  • 3
    Don't post PHP if it's not related to question. Commented Apr 19, 2017 at 12:40
  • 1
    value is for input/select and textarea, not any other element. Commented Apr 19, 2017 at 12:40
  • 1
    You are also missing semi-colon at the end of PHP Variable Commented Apr 19, 2017 at 12:41

3 Answers 3

1

.value is only use to take values of input, select or textarea fields. For html tags you need to use .innerHTML.

Change the script to this:

<script>
function rev(){
  var username = document.getElementById("name").innerHTML;
  var track = document.getElementById("track").innerHTML;
return alert (username);
}
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Accodring to w3schools defintion:

The value property sets or returns the value of the value attribute of a text field.

So try using innerHTML or textContent instead:

  var username = document.getElementById("name").innerHTML;

or

  var username = document.getElementById("name").textContent;

Comments

0

value refers to the value of an input element, while innerHTML refers to the HTML inside an element. This is an example :

<input type="text" value="foo" id="input">
<div id="div">foo</div>

In the first case you have an input, so you need to use document.getElementById("input").value, while in the second case you need to use document.getElementById("div").innerHTML.
Remember that if you have to get a value from an element in Javascript outside a function, it's better to use window.onload to make sure the elements are recognized by Javascript.
In your case, you must so use this script :

function rev() {
  var username = document.getElementById("name").innerHTML;
  var track = document.getElementById("track").innerHTML;
  return alert (username);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.