1

Is there a way to pass the value attribute from HTML side to JavaScript function via onclick event?

html/php

echo '<a href="#" class="ListOfStuff" value="' . $varVal . '" onclick="doFunction(this.value)"></a>';

javascript

<script>
    doFunction(value){
         alert(value);
    }
</script

this.value is undefined. This.id is the way I've handled it in the past, but now that i am dynamically writing a list with classnames, I don't quite understand how to pass the value from the HTML. This = [object OBJECT] and this.value is undefined. I can get the value if i use ID but not class. what am i doing wrong?

3
  • Have you tried writing onClick=doFunction(event) and then writing alert(event.target.value); in your Javascript? Commented Sep 8, 2014 at 1:07
  • Just tried it. event.target = javascript:void(0); and event.target.value = undefined Commented Sep 8, 2014 at 1:16
  • Okay then just write onclick=doFunction and function doFunction(event) {alert(event.target.value);} Commented Sep 8, 2014 at 1:18

2 Answers 2

1

Alternatively, you could use the getAttribute method to get the value. Example:

<?php

$varVal = 100;
echo '<a href="#" class="ListOfStuff" value="' . $varVal . '" onclick="doFunction(this.getAttribute(\'value\'))">test</a>';

?>

<script type="text/javascript">
function doFunction(value) {
    alert(value);
}
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

JSBin

Would something like this work for you? (using getAttribute)

HTML

<a href="#" value="myName" id="anchor" >LINK</a>

JS

  var a = document.getElementById("anchor");
a.addEventListener("click", function(event){
  event.preventDefault();
  alert(this.getAttribute("value"));
}, false);

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.