I have this in a script of mine:

function add_option(section){

var sec = section.id;
var addnew = document.myform.addnew.value;

alert('add_option: section: '+addnew);

I am pulling text from the input with the name of addnew, and it works.

I would like to use a variable in place of the "addnew" line - Here is sample HTML:

<input type="text" name="addnew-cg" value="<?php echo date(U); ?>" placeholder="Add New Option" onKeyPress="return disableEnterKey(event,cg);" />

<input type="button" value="Add" onclick="add_option(cg);"><br />

So the form name is addnew-cg, or addnew-sectionname. In the JS I need to reference addnew-+sectionname.

Is that clear? How do I use a variable in the line:

var addnew = document.myform.addnew.value;

//does not work
var addnew = document.myform.addnew+"-"+sec.value;

//does not work
var addnew = document.myform."addnew-"+sec.value;

//does not work
var addnew = document.myform.addnew-+sec.value;

Thank you!

Recommended Answers

All 3 Replies

I'm one step closer. The alert box gives me the name of the form correctly. So now the question is simply put, how can I use the variable in this line to reference the input tag name?

var addnew = document.myform.formname.value;

Here is what I have at the moment:

function add_option(section){
var sec = section.id;
var formname = "addnew-"+sec;
alert('add_option: section: '+formname);    
var addnew = document.myform.formname.value;
var x = whatever.value; // "Input's value!"

alert( x + " Hot dog!" ); // alerts: "Input's value! Hot dog!"

I appreciate the effort Martin, but it does not answer my questions. I actually just figured it out:

var sec = section.id; // get the section value
var formname = "addnew-"+sec; // name of the input field to grab
//alert('add_option: section: '+formname); // If we need to debug
var addnew = document.myform[formname].value; // grab the value of the form
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.