1,105,391 Community Members

Javascript form help with loops and variables

Member Avatar
spivey
Newbie Poster
15 posts since Feb 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I have a php foreach loop that displays a span element with a name in it, and an associated input field for each item in the array being iterated through. There is an onclick so that the value is passed to the associated input field:
<span onclick="setAuthor(this)">name</span>

Here is the statement that generates the input field ($author is generated earlier in the script).

<

form id="myform">
<input class="authors" id="authorname" type="text" name="authorname" value="' . $author . '" />

Here is my function:

function setAuthor(element) {
var author = element.innerHTML;
window.alert(author);
document.forms["myform"].elements["author_name"].value = author;
}

Right now, when I click on each name, I get distinct names as I want for the loop, but every author goes in the top field, not the input field associated with it. I can add a counter to the loop and append the counter variable to the id (authorname), to make the id distinct, but how would I reflect that in the function?

Or, if that's the wrong way of going about this, how can I get to where I want to go with this?

thanks

Member Avatar
CoursesWeb
Newbie Poster
13 posts since Mar 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Try use id="authorname" in SPAN (remove it from INPUT), then associate with name="authorname" of INNPUT:

function setAuthor(element) {
var author = element.innerHTML;
var author_name = element.id;
window.alert(author);
document.forms["myform"].elements[author_name].value = author;
}
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: