View Full Version : Find input name with input's id

06-01-2009, 11:58 PM
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?

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

Old Pedant
06-02-2009, 12:42 AM
is it possible to find the value of the input box using getElementById?

var theValue = document.getElementById("sf").value;

The longer way--clearly not needed here, but for future reference:

var fld = document.getElementById("sf");
var fldname = fld.name;
var theValue = document.f.elements[fldname].value;

06-02-2009, 01:13 AM
Everybody's favorite faq:

http://www.jibbering.com/faq/faq_notes/square_brackets.html :cool:

06-02-2009, 03:58 AM
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!

Everybody's favorite faq:

http://www.jibbering.com/faq/faq_notes/square_brackets.html :cool:

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!

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum