7

So I have some input text fields and a button

<input type=text value="a"/>
<input type=text value="b"/>
<input type=button onclick=???/>

and I want to use the values of those text fields as the parameters in a function that gets called when i click a button, say

function foo(a,b) {
    dostuff(a);
    dostuff(b);
}

I don't know what to put in the question marks. So what gets the value of the text inputs, I don't think document.getElementById gets the value of them, just the element itself.

2 Answers 2

8

There are multiple ways to access those values, but the recommended one is to start by giving the input elements ID's.

<input type=text value="a" id="a"/>
<input type=text value="b" id="b"/>

Now, you can use document.getElementById to get the element, and then the value

<input type=button onclick="foo(document.getElementById('a').value,document.getElementById('b').value)" />

Note the use of ' vs " due to them being nested...

But you could also just pass the ID's to foo, and have foo do the getElementById-stuff.

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

2 Comments

The framework was set to 'onLoad', so the foo function was captured in a closure and not available in the global scope. Set it to 'no wrap' and you should be good.
Not all browsers (IE lte 4) support getElementById. See stackoverflow.com/a/1945802/2225787
7

assign an id to inputs and then call them with getElementById

<input type="text" id="field1" value="a"/>
<input type="text" id="field2" value="b"/>
<input type=button onclick="foo('field1','field2');"/>

<script type="text/javascript">
    function foo(a,b) {
        elemA = document.getElementById(a).value;
        elemB = document.getElementById(b).value;
        dostuff(elemA);
        dostuff(elemB);
    }
</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.