0

i need to get one of the form variables dynamically in my javascript function, which takes the parameters of form and element name to be accessed in that form.

Say, i will be calling on some button click like this onClick="javascript:init(this.form, 'USERNAME')"

If i do it as : document.getElementById(formName).USERNAME.value. This works. But, i dont have to give the element name directly. I want to read it from the passed arguments.

So, if i do it as below: document.getElementById(formName).elem.value - this gives an exception saying cannot get value of undefined

function init(form, elem){
            try{
                var formName = form.name;
                var elementValue = document.getElementById(formName).elem.value;
                ..
            }catch(e){
                alert(e.message);
            }                           
        }

Kindly suggest me. How can i get the passed elem value. Thanks in advance!

1
  • 2
    It should probably be var elementValue = document.getElementById(formName)[elem].value; Commented Feb 3, 2014 at 12:56

2 Answers 2

1

In your case in order to access properties of an object you can use the following notation:

something[elem].value

Consider the following code:

var prop = "a",
    obj = {a: 1};

obj.a === obj["a"] === obj[prop];

Then your code will look like:

function init(form, elem){
    try {
        var formName = form.name,
            elementValue = document.getElementById(formName)[elem].value;
            // ...
        } catch(e) {
            alert(e.message);
        }                           
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Make a button to pass the value to the javascript. The button will get the value(ex: from textbox) and will pass it to the javascript.

So,

<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="init(document.getElementById('textbox1').value)" type="button" value="Execute" />

1 Comment

Yes sughan90, your suggestion makes sense. I will follow the same. Thanks!

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.