Jay Welsh
Jay Welsh

Reputation: 496

Set value of button clicked as a Javascript variable - without using an ID/Name

Is it possible for me to carry the value of a button over to the function that that the button executes?

Simple concept, how would I get the value "5" to be carried over to my function where I can define it as a variable?

<button onclick="functionHere()" value="5">Delete</button>

Code actually looks more like:

<button onclick="functionHere()" value="' + aData[5] + '">' + 'Delete</button>

Upvotes: 1

Views: 4486

Answers (2)

AtheistP3ace
AtheistP3ace

Reputation: 9691

In your example you can reference the button element using this.

HTML:

<button onclick="functionHere(this)" value="' + aData[5] + '">' + 'Delete</button>

JS:

function functionHere (btn) {
    var buttonValue = btn.value;
}

this references the context of the function. So in this case since the function was called by setting it as the onclick of the button, the functions context is the button element.

EDIT: I am mistaken actually this doesn't seem to be set automatically when used how you use it. Code updated. Here is a fiddle: http://jsfiddle.net/9nv4sz6L/

Upvotes: 1

user3320657
user3320657

Reputation:

You can do it like this.

<input type="button" value='Hello World' onclick='ShowValue(this)'/>

<script>
    function ShowValue(btn){  
        alert(btn.value);
    }
</script>

Upvotes: 0

Related Questions