2

I'm trying to access form data through a Javascript function when an input is 'changed'. Currently I use something like this:

<form>
    <input type="radio" name="type" name="myValue" onchange="myFunction(this.form)>
</form>

<script>
    function myFunction(form) {
        var value = form.type.value;
    }
</script>

And it works, however instead of writing

var value = form.type.value;

I need to write something like this

var myArray = ["type"];
var value = form.myArray[0].value;

Which is not working. Is this due to how values in arrays are handled?
I have it here on JSFiddle if that is useful.
Thanks

3 Answers 3

2

Try

var value = form[myArray[0]].value;

form.myArray[0] is first getting the member myArray from form, and then trying to get the first item in that. Equal to (form.myArray)[0]

form[myArray[0]] explicitly says get the member from form which is of the name of the value inside myArray[0]

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

Comments

0

You can access properties of object using [] like this:

var value = form["type"].value;
// equivalent to:
var value = form.type.value

In your case this should work:

var myArray = ["type"];
var value = form[myArray[0]].value;

Comments

0

'myArray' is declared as a local variable but it is NOT form's property. So form.myArray will fail.

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.