1

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>
5
  • 3
    Short answer: Yes Hope you won't mind sharing the code. Commented Oct 14, 2015 at 13:09
  • As previous comment said yes, but perhaps some example of your code could help us show you precisely how. Using anonymous functions, scope and closures will do this for you easily. Commented Oct 14, 2015 at 13:10
  • I don't think value is a legal attribute of anchor. EDIT: Cool, you changed it. button can have value. Commented Oct 14, 2015 at 13:14
  • @AtheistP3ace changed it to an actual button. Commented Oct 14, 2015 at 13:18
  • @Satpal Added the code :) Commented Oct 14, 2015 at 13:19

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately the value is showing up as undefined. Does the button need to be within a form? I think it might be worth stating this too: The value is set in a javascript callback function, this function produces the button with its value and results in the html looking as I showed in my original question.
Yea for some reason I thought this would be set automatically when you put function directly in on click attribute but it seems you need to pass it. Button doesn't have to be in form and building the html dynamically should be fine.
You're quite welcome. Sorry for the confusion. Haven't finished my coffee yet this morning. :)
0

You can do it like this.

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

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

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.