1.11M Members

JavaScript Syntax help simple

 
0
 

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!

 
0
 

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;
 
0
 
var x = whatever.value; // "Input's value!"

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

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
Question Answered as of 2 Years Ago by MartinRinehart
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: