Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Nov 2007
    Posts
    36
    Thanks
    1
    Thanked 0 Times in 0 Posts

    passing name of field to javascript function and getting its value

    I want to pass name of form field to a JavaScript function and get its value

    like

    function getValue(fldName)
    {

    sel_val = document.mcqReport.fldName.value;

    }

    Here mcqReport is formname
    and i call this function like

    getValue("txtUserName");
    getValue("txtUseEmail");

    txtUserName and txtUseEmail are two input fields of my form. But it gives error

    Error: document.mcqReport.fldName is undefined

    Please can you help me how i can do this.

    Thanks

  • #2
    GŁtkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    It's undefined because there is no field with the name 'fldName'. In order to use the value of the variable fldName, and not the literal string 'fldName', you have to use

    Code:
    sel_val = document.mcqReport[fldName].value;

  • #3
    New Coder
    Join Date
    Nov 2007
    Posts
    36
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks Dear.

    What if i am using an arry. Like if fld is an array of check boxes.
    will i access its values in document.frmReport[fld][0].value ??

    Quote Originally Posted by venegal View Post
    It's undefined because there is no field with the name 'fldName'. In order to use the value of the variable fldName, and not the literal string 'fldName', you have to use

    Code:
    sel_val = document.mcqReport[fldName].value;

  • #4
    GŁtkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    If fld is an array containing the names of your checkboxes, and 'frmReport' is the name of the form, you can access the first one with

    Code:
    document.frmReport[fld[0]].value


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •