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
    May 2005
    Posts
    78
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Find input name with input's id

    I'm building a page which has an input box that frequently changes its name attribute using innerHTML. However, the id ("sf") always stays the same. How would I find the current name of the input using JavaScript? And is it possible to find the value of the input box using getElementById? If not, how would I find the value of the input box, if the name changes?

    For instance...say the name was "q". I would access it normally using document.f.q.value. However, since the name changes, that won't always work. If I were to find the name, and then set it to a variable, how would I then find the value of the input? Say the variable would be "qvar"...wouldn't document.f.qvar.value look for an input with the name "qvar"? Would 'document.f.'+qvar+'.value' work?

    Code:
    <form name="f">
    <input type="text" name="q" id="sf">
    </form>

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,622
    Thanks
    80
    Thanked 4,635 Times in 4,597 Posts
    is it possible to find the value of the input box using getElementById?
    Yes.
    Code:
    var theValue = document.getElementById("sf").value;
    The longer way--clearly not needed here, but for future reference:
    Code:
    var fld = document.getElementById("sf");
    var fldname = fld.name;
    var theValue = document.f.elements[fldname].value;

  • Users who have thanked Old Pedant for this post:

    ikilledsanta (06-02-2009)

  • #3
    Senior Coder
    Join Date
    Jun 2002
    Posts
    1,404
    Thanks
    2
    Thanked 32 Times in 32 Posts

  • #4
    New Coder
    Join Date
    May 2005
    Posts
    78
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    Code:
    var theValue = document.getElementById("sf").value;
    ]
    Wow. That was incredibly simple...I thought I had tried that before, I guess I must have done something wrong. It works great. Thanks!

    Quote Originally Posted by adios View Post
    I had no idea bracket notation applied to so many things. I've used them before in frames, and some other things...I will definitely remember it in the future!


  •  

    Posting Permissions

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